Declaring an ArrayList
Please review the code below:
What is the real difference between arrayList1 and arrayList2? Both works the same ????
Collection <String>arrayList1 = new ArrayList<String> ();
ArrayList <String>arrayList2 = new ArrayList<String> ();
arrayList1 and arrayList2 are both instances of ArrayList, but they are of different type. arrayList1 can contain a Collection object. Although arrayList1 is actually an ArrayList, the compiler will see it as an object of type Collection. To use arrayList1 as an ArrayList you must first cast it. arrayList2 is an object of type ArrayList and no cast is necessary. But, in essence they are both still ArrayList objects.
Does that help? :D
Thanks Tim. It means both can only store ArrayLists. Even arrayList1 cannot store other collections. Is this so?
That is not true. arrayList1 can store any instance of Collection, but arrayList2 can only store instances of ArrayList or any subclasses of it. For example:
Originally Posted by bugger
The following is okay
Collection <String> test1 = null;
ArrayList <String> test2 = null;
The following is NOT okay
test1 = new ArrayList<String>();
test1 = new Vector<String>();
test2 = new ArrayList<String>();
These are polymorphism concepts. I am sorry if I confused you. :o I'm trying my best to explain this.
test1 = new Integer(10);
test2 = new Vector<String>();