Can Any one tell me the difference between these two statements
List list = new ArrayList();
ArrayList list = new ArrayList();
In an interview, i got this question..........please answer it.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Can Any one tell me the difference between these two statements
List list = new ArrayList();
ArrayList list = new ArrayList();
In an interview, i got this question..........please answer it.
Ok, well List is an interface, which means it cannot be initalized. ArrayList implements List, so that's where it gets some of its methods from.
I think (not entirely sure on this), but by saying List list new ArrayList(), you are creating a new ArrayList, but limiting it to the methods given to it by the List interface. Whereas saying ArrayList list = new ArrayList(), you are creating a new ArrayList with full access to the ArrayList methods.
I think thats it, but I'm not entirely sure. I learned the purpose of that like a year or two ago, and I use it alot when I create my own Listeners, but I cant exactly remember what it restricts. The more I think about it, the more I think I may be wrong.
List is an interface which ArrayList implements. Doing so allows you access to all the implemented methods provided by the List interface, without worrying about how the List is implemented. This is a very common and powerful method to pass around objects, as it helps make a program loosely coupled. A simple example might be the following: you've written an class (call it say ListReturn) which contains a method that returns an ArrayList - call this method listReturn(). Considering that many other objects utilize listReturn(), returning an ArrayList makes all those methods dependent upon ArrayList. Now suddenly you need to change your program to a multithreaded environment and need to synchronize things (ArrayList is not syncrhonized), returning an ArrayList from listReturn() forces you to update all the other classes, whereas returning just a List allows you to make the change in a single object - ListReturn (for example using Collections.synchronizedList or a Vector). Just another form of encpaculation
Last edited by copeg; July 12th, 2010 at 10:23 AM.