In this statement List<String> MyList = new ArrayList<String>();
Why declare Mylist as a List of type String. just to make MyList a new instance of an ArrayList type String?
It seems unnecessary.
In this statement List<String> MyList = new ArrayList<String>();
Why declare Mylist as a List of type String. just to make MyList a new instance of an ArrayList type String?
It seems unnecessary.
To paraphrase Item 52 of Joshua Bloch's Effective Java, using the interface instead of the class makes the surrounding code much more flexible. So if you wanted to change myList
to something like a Vector, you wouldn't have to change the surrounding code much if at all. Bloch goes on to say that there are certain times, such as major updates to java, when other types of Lists are updated for effectiveness or new ones are added entirely.
Declaring MyList
as type List<String>
guarantees that you won't use methods only available for ArrayList<String>
. That way, you can change the right-hand side of the declaration in the future.
List
is just an Interface, not an implementation. There are many different types of lists, such as ArrayList
and LinkedList
.
So if you declare MyList
an List<String>
it could possibly be any type of List
, as @espertus said, you can change what type of list MyList
is in the future without having to change it's declaration.