This question has already been answered:

And yet, somebody can explain in detail what is different with Set<String> set1 = new HashSet<String>(); and HashSet<String> set1 = new HashSet<String>(); ?

Reported as a duplicate by the participants of zRrr , pavlofff , ermak0ff , pavel , cheops 8 Nov '16 at 6:50 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Questions about the use of site functions should be asked on the site - pavlofff

1 answer 1

java.util.Set is an interface, not a class.
HashSet implements the Set interface.
Set set1 = new HashSet(); creates an object of type HashSet and assigns a reference to the object of a variable of type Set .

HashSet set1 = new HashSet(); creates an object of type HashSet and assigns a reference to the object of a variable of type HashSet .

That is, these two examples of initialization differ in the way HashSet stored. For example, initialization Set set1 = new HashSet(); allows you to "redo" HashSet in TreeSet .

PS I forgot to add that in OOP it is considered good form to declare variables with an interface type, since code needs to be written in the most general form.