public class SomeClass {
private HashSet<SomeObject> contents = new HashSet<SomeObject>();
private Set<SomeObject> contents2 = new HashSet<SomeObject>();
}
What’s the difference? In the end they are both a HashSet isn’t it? The second one looks just wrong to me, but I have seen it frequently used, accepted and working.
Setis an interface, andHashSetis a class that implements theSetinterface.Declaring the variable as type
HashSetmeans that no other implementation ofSetmay be used. You may want this if you need specific functionality ofHashSet.If you do not need any specific functionality from
HashSet, it is better to declare the variable as typeSet. This leaves the exact implementation open to change later. You may find that for the data you are using, a different implementation works better. By using the interface, you can make this change later if needed.You can see more details here: When should I use an interface in java?