Java Reference
In-Depth Information
method must be of the Date type. Since the errors can be detected at compile time rather than
at runtime, the generic type makes the program more reliable.
ArrayList was introduced in Section 11.11, The ArrayList Class. This class has been a
generic class since JDK 1.5. Figure 19.3 shows the class diagram for ArrayList before and
since JDK 1.5, respectively.
reliable
java.util.ArrayList
java.util.ArrayList<E>
+ArrayList()
+add(o: Object): void
+add(index: int, o: Object): void
+clear(): void
+contains(o: Object): boolean
+get(index:int): Object
+indexOf(o: Object): int
+isEmpty(): boolean
+lastIndexOf(o: Object): int
+remove(o: Object): boolean
+size(): int
+remove(index: int): boolean
+set(index: int, o: Object): Object
+ArrayList()
+add(o: E): void
+add(index: int, o: E): void
+clear(): void
+contains(o: Object): boolean
+get(index:int): E
+indexOf(o: Object): int
+isEmpty(): boolean
+lastIndexOf(o: Object): int
+remove(o: Object): boolean
+size(): int
+remove(index: int): boolean
+set(index: int, o: E): E
(a) ArrayList before JDK 1.5
(b) ArrayList since JDK 1.5
F IGURE 19.3
ArrayList is a generic class since JDK 1.5.
For example, the following statement creates a list for strings:
ArrayList<String> list = new ArrayList<>();
You can now add only strings into the list. For instance,
only strings allowed
list.add( "Red" );
If you attempt to add a nonstring, a compile error will occur. For example, the following state-
ment is now illegal, because list can contain only strings.
list.add( new Integer( 1 ));
Generic types must be reference types. You cannot replace a generic type with a primitive
type such as int , double , or char . For example, the following statement is wrong:
generic reference type
ArrayList< int > intList = new ArrayList<>();
To create an ArrayList object for int values, you have to use:
ArrayList<Integer> intList = new ArrayList<>();
You can add an int value to intList . For example,
intList.add( 5 );
Java automatically wraps 5 into new Integer(5) . This is called autoboxing , as intro-
duced in Section  10.8, Automatic Conversion between Primitive Types and Wrapper
Class Types.
autoboxing
 
 
Search WWH ::




Custom Search