import java.util.*;
public class ArrayListTest {
public static void main(String[] args) {
// I understand that arraylist only hold object types and
// they did not hold primitive types right?
// Yes. In j2se 1.5 autoboxing was introduced so you
// can treat them as if they will accept primitives.
List<Integer> list1 = new ArrayList<Integer>();
list1.add(Integer.valueOf(1));
list1.add(2);
System.out.printf("list1.get(0) = %d list1.get(1) = %d%n",
list1.get(0), list1.get(1));
// If you want to convert object type to primitive type you
// have to use wrapper class or casting is it?
// Before j2se 1.5 - yes. You can still do this after v1.5
List<Integer> list2 = new ArrayList<Integer>();
list2.add(Integer.valueOf(21));
int day1 = ((Integer)list2.get(0)).intValue();
int day2 = list2.get(0).intValue();
System.out.printf("day = %d day2 = %d%n", day1, day2);
// Must data type be declared for creating new ArrayList?
// In j2se 1.5+ it is recommended but not required. If you
// don't you can get "Xlint:unchecked" compiler warnings
// which can be suppressed in later versions.
List list3 = new ArrayList(); // compiler warning
List<String> list4 = new ArrayList<String>();
// If I use the arraylist get() method with or without data
// type declaration is it return object type?
list3.add("hello");
list4.add("world");
System.out.println("list3.get(0) type = " +
list3.get(0).getClass().getName());
System.out.println("list4.get(0) type = " +
list4.get(0).getClass().getName());
// You don't have to cast from Object to specific type if
// you use generic types. You do need to cast if you do not
// use generic types.
//String sx = list3.get(0); // compile error
String s3 = (String)list3.get(0);
String s4 = list4.get(0);
}
}