-2

I've started getting back to java and I have a general question about defining a constructor for an object: I'm following a tutorial where he defines a HashSet object by the following statement:

Set<String> set = new HashSet<String>(list);

(list is a List object)

And I was wondering what's the difference if I use this statement:

HashSet<String> set = new HashSet<String>(list);

thanks!

ysap
  • 7,723
  • 7
  • 59
  • 122

2 Answers2

0

This relates to one of most important concepts of oops, i.e. polymorphism. If you use HashSet in place of set then you will not be able to build flexible code. Say, if you want to pass the object as an argument to a method then if you use Set interface someday you can pass another implementation like TreeSet and the method will work properly. This makes the code loosely coupled.

sam_haz
  • 189
  • 3
  • 15
0

One of the defining characteristics of the Java Collections Framework is that it is an interface-based type system. The API is defined largely through interfaces that may extend other interfaces. The base interface is Collection.

In this way, most of the collection implementations (eg. ArrayList, HashSet, etc.) are also assignable to variables or parameters of type Collection). This provides a lot of expressive power to the Framework.

Most of the Java Collection Framework implementations have a constructor that accepts a parameter of type Collection. This is called the "conversion constructor" because it allows you to pass in any collection in the framework whose type extends the Collection interface (and most do) and get that collection represented as a collection of the newly constructed type.

In other words:

List<String> list1 = Arrays.asList(new String[] { "one", "two", "three" });
HashSet<String> set1 = new HashSet<>(list1);

The variable set1 will end up containing a reference to a HashSet instance containing all the objects that are also in the List instance list1. The conversion constructor, in effect, converted the representation of your data from a List to a HashSet.

Whenever possible, it is typically a best practice to use an object's interface as its type rather than its implementation type. This gives you much greater flexibility. Therefore "List myList = ..." is preferred over "ArrayList myList = ...".

scottb
  • 9,908
  • 3
  • 40
  • 56