0

In most of the examples JAVA collection objects are instantiated as:

List <String> l1 = new LinkedList<String>();

Set<String> s1 = new HashSet<String>();

Instead of:

LinkedList<String> l1 = new LinkedList<String>();

HashSet<String> s1 = new HashSet<String>();

What is the difference in these method of instantiation ?

Nurjan
  • 5,889
  • 5
  • 34
  • 54
user1743514
  • 311
  • 1
  • 3
  • 21

1 Answers1

0

Java provided an interface which can be implemented by the classes as it's general contract. So, the classes that implement a certain interface need to have all the methods of the interface implemented in them. The Java set and list are two such interfaces and the linkedlist or an Arraylist is an implementation of the list interface. Same for a set. The reason why you write an interface on the left hand side is because it is considered a good style to just limit the functionality of the data structure to satisfy the requirements you need. It is better to use a List if you want just a List functionality rather than using a broader idea- this makes it less prone to bugs. The reason why you write a Linkedlist or an Arraylist on the right hand side is because interfaces in Java can not be instantiated (This is in line with the fact that you have no implementation in interfaces).

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Moonstruck
  • 503
  • 4
  • 10