Collection
classes
get
and methods instead
- full-fledged member of the class hierarchy
toString
method
- many useful 'vector-like' methods: contains, insert, remove, addAll
Like all the other collection classes:
Object
element type
Object
at root
ArrayList alist = new ArrayList(); // Object element type for (int i = 1; i < 10; i++) { Integer integer = new Integer(i); // wrapping primitive int in Integer wrapper object alist.add(integer); // upcast of Integer to Object element type } for (int i = 0; i < alist.size(); i++) System.out.println(alist.get(i)); // no cast downcast necessary -- calling toString which is defined in Object for (int i = 0; i < alist.size(); i++) { Integer integer = (Integer)alist.get(i)); // downcast of Object to Integer int n = integer.intValue(); // extraction of primitive int from Integer wrapper n++; // int operation integer = new Integer(n)); // wrapping primitive int in (new) Integer wrapper object alist.set(i, integer); // upcast Integer to Object element type, replacing original element at i }
ArrayList arrList = new ArrayList(); while (...) { // adding String's to the vector String s = ...; arrList.add(s); } ... for (int i = 0; i < arrList.size(); i++) { String s = (String)arrlist.get(i); // downcast needed … }
ArrayList<String> arrList = new ArrayList<String>
ArrayList<String> arrList = new ArrayList<String> v.add(new Integer(5)); // compiler error
ArrayList
can only contain String
s
ArrayList<String> arrList = new ArrayList<String> String s = ...; arrList.add(s); ... String s2 = arrList.elementAt(0); // no need for downcast-- compiler takes care of it
ArrayList<Strin>> v = new ArrayList<String>(); while (...) { // adding String's to the vector String s = ...; arrList.add(s); } ... for (int i = 0; i < arrList.size(); i++) { String s = arrlist.get(i); // no downcast needed … }
Object
s.
for (element-declaration : iterable) use element in loop body
Random r = new Random(); ArrayList<Integer> arrList = new ArrayList<Integer>(); for (int i = 0; i < 100; i++) arrList.add(new Integer(r.nextInt(200))); for (Integer i : arrList) System.out.println(i);
ArrayList<Integer> arrList = new ArrayList<Integer> ... arrList.add(3); // compiler automatically insert a 'new Integer(3)'
ArrayList<Integer> arrList = new ArrayList<Integer> ... int i = arrList.get(0); // compiler automatically insert a '.intValue()'
ArrayList<Integer> arrList = new ArrayList<Integer>();i.e., the generic type argument needs to be specified in both the declaration of the reference variable as well as in the creation of the object.
ArrayList<Integer> arrList = new ArrayList<>();
<>
is called the diamond operator