| Author |
Difference Between These 2 Declarations.
|
Suresh Rajadurai
Ranch Hand
Joined: Feb 22, 2007
Posts: 58
|
|
Hi Gurus, Please explain the difference between these two declarations. ArrayList myList = new ArrayList(); List myList = new ArrayList(); Regards Suresh.
|
 |
Thirugnanam Saravanan
Ranch Hand
Joined: Dec 13, 2007
Posts: 81
|
|
Hi Suresh
This is an ordinary instantiation of the Class ArrayList.
This is where Polymorphism came into picture in java. You should have heard some where that :
A reference variable can refer to any object of the same type as the declared reference, or�this is the big one�it can refer to any subtype of the declared type!
Here the List Interface Reference variable (myList) is referring to its subtype (in this case its implementing class ArrayList Type). In addition to ArrayList , it can refer any of its subtype like LinkedList,Vector etc.. Let me know if you need more information on this. [ February 08, 2008: Message edited by: Thirugnanam Saravanan ]
|
Saravanan
SCJP 5.0(98%), SCWCD 5.0 (100%), OCA
|
 |
Sheikh Sadiruddin
Greenhorn
Joined: Aug 10, 2007
Posts: 21
|
|
|
Can someone tell us which declaration is good for programming.
|
SCJP 6 (80%) || SCWCD 5 (92%)
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32675
|
|
Neither. You should say
|
 |
Peter Chase
Ranch Hand
Joined: Oct 30, 2001
Posts: 1970
|
|
Campbell, I think you needed to explain your post more - this is the Beginner forum. The original question was about variables that refer to collection objects. Should one declare them as being of the exact type (e.g. ArrayList) or of the implemented interface (e.g. List)? The answer is "it depends". Declaring as ArrayList is more restrictive. If there is a good reason why only an ArrayList would be suitable, then you should declare the variable as an ArrayList. This also may give very slightly better performance, due to simplified method dispatch, but don't get excited about that. Declaring as List is more flexible. If there is good reason to think that ArrayList is not the only kind of List that could be used, then it is better to declare the variable as a List. This allows the code to be changed very simply in the future, if another kind of List is deemed suitable. I think that point that Campbell was making is that, if using Java 5 or better, collections should always be declared with a type ("generics"). If your List is only going to be storing objects of class Foo (or subclass), declare it as List<Foo>. This will make your code more concise, and also allows the compiler to spot certain types of bugs, which it could not spot if you used a plain List.
|
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32675
|
|
|
Yes, Peter, you are right. You have explained what I ought to have explained myself.
|
 |
 |
|
|
subject: Difference Between These 2 Declarations.
|
|
|