-1

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.

user2998504
  • 75
  • 1
  • 5
  • 13
  • 2
    In that way, if tomorrow your boss says, "I don't want ArrayList in my code cause reminds me my ex-wife put `LinkedList` instead". So then you ensure that you only have to change 1 line.. that is object creation `new LinkedList<>()`, You follow a contract rather than an implementation, you forget about implementation details. – nachokk Mar 17 '14 at 01:23
  • @ Sotirios Delimanolis and PakkuDon, good boys have a cookie... – user2998504 Mar 17 '14 at 01:26

3 Answers3

4

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.

user2837058
  • 140
  • 7
1

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.

Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
1

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.

Yep_It's_Me
  • 4,494
  • 4
  • 43
  • 66