0

I'm new to Java and I'm coding just for fun, and I'm wondering about this.

Set<Employee> employees1 = new HashSet<Employee>();
HashSet<Employee> employees2 = new HashSet<Employee>();

Is there any difference in those two declarations ? I mean like " behind the scenes " ? I was looking for similar problem here, but I didn't find anything maybe because I don't know how to interpret the question in search field.

gprathour
  • 14,813
  • 5
  • 66
  • 90
George
  • 3
  • 1
  • 3
    `Set` is an interface. `HashSet` is an implementation of that interface. If you say `Set`, you can swap out the HashSet for any other implementation (of Set) you want (at runtime). – byxor Jun 23 '17 at 11:05
  • Look up interitance/polymorphism. It should clear some things up for you. – DCON Jun 23 '17 at 11:07
  • And the main advantage of using first declaration is abstraction, which will give you the chance to switch Set implementation (to SortedSet for example) in the future. – mulya Jun 23 '17 at 11:10

2 Answers2

2

Set is an interface, where as HashSet is a class implementing that interface.

Set<Employee> employees1 = new HashSet<Employee>();

By reference variable employees1 you can call only those methods of HashSet class which are declared in Set interface and overridden in HashSet.

HashSet<Employee> employees2 = new HashSet<Employee>();

By using employees2 you will be able to call overridden methods of Set interface and HashSet class's own methods (which are not declared in Set interface.)

gprathour
  • 14,813
  • 5
  • 66
  • 90
  • 2
    And the main advantage of using first declaration is abstraction, which will give you the chance to switch Set implementation (to SortedSet for example) in the future. (copied this comment to question itself) – mulya Jun 23 '17 at 11:09
  • @mulya nice point – gprathour Jun 23 '17 at 11:10
  • 2
    Choosing to use an interface is like sending your future self a surprise gift. – byxor Jun 23 '17 at 11:12
0

Set is an interface, while HashSet is one of its implementations.

If your variable is declared Set, it could have other implementations as value. EG:

employees1 = new TreeSet<Employee>();
Usagi Miyamoto
  • 6,196
  • 1
  • 19
  • 33