This question already has answers here:
What is the difference between the HashMap and Map objects in Java?
(13 answers)
Closed 8 years ago.
I am trying to understand what is the difference between the below 2 lines of code.
I know for a reason that one is of the reference type List and the other of the reference type ArrayList. But does it really matter or is it just 2 different ways of doing the same thing ?
Its not only with these classes/interface but with others as well. I believe it is a Polymorphism feature of an object taking different forms is that correct ?
List a1 = new ArrayList();
ArrayList a1 = new ArrayList();
You don't declare objects, you declare variables (and members).
The difference in the interface you have to the object. In the first case, the interface is List, whereas in the second it's ArrayList. The underlying object is the same, but you have different access to it. In theory, ArrayList could have methods that List doesn't have (although in practice I don't think it does).
The advantage to using List is that you can change the underlying object to be a different kind of list (by changing what kind you create) without breaking your contract with any code that's using it. If you declare it as ArrayList, you have to change your contract if you want to change the underlying implementation.
Disclosure: This is an adapted form of my answer to this question. It's basically the same question, but you probably wouldn't find it when looking with the terms you were using. :-)
List a1 is an interface meaning that for example it can reference a LinkedList as well (doesn't restrict the implementation to ArrayList).
While ArrayList a1 can be only assigned ArrayList instances, which is a restriction you don't wish to have sometimes.
It is usually considered better approach to use interfaces (List, Map etc.) instead of concrete types especially if you expose methods to external apps, therefore you don't enforce implementation details. You just expect the variable a1 to behave as a List.
List is an interface, ArrayList implements that interface.
List a1 = new ArrayList();
a1 will be a List variable that contains an instance of the object ArrayList, the cast of the new ArrayList to List will be done implicitly.
It does have to do with inheritance/polymorphism. Think of it as similar to:
Animal dog1 = new Dog();
Dog dog2 = new Dog();
Both will let you perhaps .eat(), but only dog2 can .bark()
Related
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 6 years ago.
If we consider two implementations below, what's the actual use of the first one?
List<String> a= new ArrayList<String>();
ArrayList<String> b= new ArrayList<String>();
From what I have read in the posts, the first implementation helps in avoiding breaking change like we can change the implementation again as
a=new TreeList<String>();
But I don't understand whats the actual use of changing the implementation with treelist as we can use only the List interface methods?
But I don't understand whats the actual use of changing the implementation with treelist as we can use only the List interface methods?
Different implementations of interface List have different performance characteristics for different operations. Which implementation of List you should choose is not arbitrary - different implementations are more efficient for different purposes.
For example, inserting an element somewhere in the middle is expensive on an ArrayList, but cheap on a LinkedList, because of the way the implementations work. Likewise, accessing an element by index is cheap on an ArrayList, but expensive on a LinkedList.
It may happen that when you started writing your program, you used an ArrayList without thinking about it too much, but later you discover that a LinkedList would be more efficient.
When you've programmed against the interface List instead of a specific implementation, it's very easy to change from ArrayList to LinkedList - to the rest of the program, it still looks like a List, so you'd only have to change one line.
Lets say that you have decided to develop a more efficient List implementation of your own. Perhaps one that has better memory management internally, or may be a faster set method (insertion) implementation. You can just implement the List interface and rest of your code will continue to work without any change, except this one line. You can also extend ArrayList and write your own code.
//Old code
List<String> a = new ArrayList<String>();
a.set(0, "Test");
//New code
List<String> a = new MyCustomisedList<String>();
//Same code, but your optimized set logic. May be faster...
a.set(0, "Test");
A TreeList doesn't exist, so lets use a PersistentList as an example.
Lets say you have an #Entity that you want to save to a database:
public class MyMagicEntity {
#OneToMany
List<MyChildEntity> children;
public void setChildren(final List<MyChildEntity> children) {
this.children = children;
}
}
Now, when you create MyMagicEntity then you would do something like
final MyMagicEntity mme = new MyMagicEntity();
final List<MyChildEntity> children = new ArrayList<>();
children.add(new MyChildEntity("one"));
children.add(new MyChildEntity("two"));
children.add(new MyChildEntity("three"));
mme.setChildren(children);
//save to DB
So you created an ArrayList that you passed into your MyMagicEntity, which assigns it to the List - it doesn't care that the underlying implementation is as long as it's a List.
Now, later you do:
final MyMagicEntity mme = //load from DB
final List<Children> children = mme.getChildren();
So, what is children? Well, if we are using JPA and Hibernate it is actually a PersistentList, not an ArrayList.
As we access the members of children, Hibernate will go and pull them from the database. This List is still a List - your program doesn't have to know any of this.
Could you do this without using the List interface? No! Because:
you cannot create a PersistentList
Hibernate cannot create an ArrayList
Whilst this is an extreme example, where the underlying behaviour of the List is completely different, this applies in all sorts of other situations.
For example:
ArrayList and LinkedList have different performance characteristics, you may want to switch
Guava has an ImmutableList which you may want to use
Collections.unmodifyableList also implements List, which you may want to use
You could conceivably have a List backed by a file
The basic idea is that List defines what any list must be able to do, but not how it is done.
Here List is an Interface which contains all common operation method can perform with an List.
List Interface is parent for ArrayList , LinkedList and many more class. So, It can hold all these type of Object reference.
All these List method have different (or own type) Implementation with different class. So, whatever method you use will automatically apply according to override method definition of Object belong to the class.
List<String> a= new ArrayList<String>();
ArrayList<String> b= new ArrayList<String>();
Now , In Your case you can declare both ways is alright. but suppose a Scenario like this.
You are calling some services and you know that return any List Type (not specific) of Object. It may be a LinkedList or ArrayList or any other type of List.
at that time whatever response you get You can easily hold those responses in a List Type of Reference Variable.
and after gathering the result you can differentiate further of Object Type.
This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
List versus ArrayList as reference type?
(3 answers)
Closed 9 years ago.
Is there a difference between these two? If so, what is it?
List<Integer> x = new ArrayList<Integer>();
and
ArrayList<Integer> x = new ArrayList<Integer>();
The first declaration lets you program to interface. It ensures that later on you can safely replace ArrayList with, say, LinkedList, and the rest of code is going to compile.
The second declaration lets you program to the class, so you could potentially use methods of ArrayList which do not implement the List interface. For example, you can call ensureCapacity() on the list declared as ArrayList, but not on a list declared as List. Although generally programming to interface should be preferred, there is nothing wrong with doing it if you must call class-specific methods: for example, ability to call ensureCapacity() could save some unnecessary reallocations if you know the new target size of your list.
The former is preferred. It allows changing the implementation without changing code that depends on the field.
In Effective Java, Joshua Bloch says:
If appropriate interface types exist, then parameters, return values, variables and fields should all be declared using interface types.
...
If you get into the habit of using interfaces as types, your program will be much more flexible.
If you code to interfaces then you can change the implementation without much hassle
List<Integer> x = new ArrayList<Integer>();
you can make x now point to a LinkedList or any other implementation of List with only one line of code. If you need a specific method that is in ArrayList then having ArrayList on the left hand side is perfectly acceptable. 99 times out of 100 thought you wont so List is preferred
With ArrayList you can specify an intitalsize and so ArrayList has trimToSize() method to trim its size to the current size.With List<Integer> you won't be able to trim the size unless you cast it back to ArrayList
This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
Closed 9 years ago.
I have observed in Java programming language, we code like following:
List mylist = new ArrayList();
Why we should not use following instead of above one?
ArrayList mylist = new ArrayList();
While the second option is viable, the first is preferable in most cases. Typically you want to code to interfaces to make your code less coupled and more cohesive. This is a type of data abstraction, where the user of mylist (I would suggest myList), does not care of the actual implementation of it, only that it is a list.
We may want to change the underlying data structure at some point, and by keeping references, we only need to change the declaration.
The separation of Abstract Data Type and specific implementation is one the key aspects of object oriented programming.
See Interface Instansiation
Just to avoid tight coupling. You should in theory never tie yourself to implementation details, because they might change, opposite to interface contract, which is supposed to be stable. Also, it really simplifies testing.
You could view interface as an overall contract all implementing classes must obey. Instead, implementation-specific details may vary, like how data is represented internally, accessed, etc. - the information that you'd never want to rely on.
If you use ArrayList, you are saying it has to be an ArrayList, not any other kind of List, and to replace it you would have to change every reference to the type. If you use List you are making it clear there is nothing special about the List and it is used as a plain list. It can be changed to another List by changing just one line.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why should the interface for a Java class be prefered?
I m relatively new to java and i have just started on collections framework.
While on ArrayList I encountered on two ways people declare it. For example to declare an ArrayList of Strings :
List<String> l = new ArrayList<String>();
or
ArrayList<String> al = new ArrayList<String>();
Which one of these two should I use and what is the difference between them?
I know that the actual methods called are decided at runtime and hence the methods called will all be of ArrayList class only but still the first declaration restricts the methods that can be called.
The first way is, I have heard, called "coding to an interface". Any method will be invoked using the variable l and hence only methods provided by List interface can be called, whereas, in the second example we can call all the methods provided not only by List but by the Object class also (like finalize(), wait() etc). So why even in the first place people even use the first declaration??
You should always use least specific interface possible. This makes it easier to substitute alternate implementations if a more appropriate one exists. For example, methods that take List don't care if the list is a linked list or an array list. You can choose whichever one is more appropriate.
I personally recommend using List<String> l = new ArrayList<String>();
The reason is you typically don't need to know you're working with an ArrayList. You just need something that operates like a list. There's a lot of behaviors on ArrayList that people don't need access to. Consider "EnsureCapacity". They don't need that - they just need the List operations. As a general rule, you want to limit the exposure of data and functionality on a "need to know" basis, and users of your list do not need to know (by default) what implementation you used.
Obviously, if they do need to know that you're using an ArrayList instead of a LinkedList, for instance, then you would want to use an ArrayList reference instead of a List reference. For most purposes though, that's not necessary.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Type List vs type ArrayList in Java
Why is it recommended to do this:
List<String> myArrayList = new ArrayList<String>
or same with Map interface and HashMap class
rather than:
ArrayList<String> myArrayList = new ArrayList<String>
Because the consuming code of the myArrayList variable won't be tied to a particular implementation of this interface.
With the first (preferred) line you say, that your code needs a List, with the second line you say your code needs an ArrayList. Usually, you path variable instances around. If you now change the myArrayList instance for some reason you would have to change too much code.
You should not use:
List<String> myArrayList = new ArrayList<String>
Why you should use the type List instead of ArrayList (unless you really need feature of the ArrayList that is missing in the List interface) is already explained in the other answer.
But I think it is even more important to use proper names. So if you use List as type for the variable, the name should not tell that it is an ArrayList. It would be even better if the name indicated the use of the variable.
Yes, this is picky. But using good names will make it a lot easier to understand the code in a year from now and for colleagues.