Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between these two java variable declarations?

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.

like image 304
The Surrican Avatar asked Mar 21 '26 18:03

The Surrican


1 Answers

Set is an interface, and HashSet is a class that implements the Set interface.

Declaring the variable as type HashSet means that no other implementation of Set may be used. You may want this if you need specific functionality of HashSet.

If you do not need any specific functionality from HashSet, it is better to declare the variable as type Set. 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?

like image 157
Alan Geleynse Avatar answered Mar 24 '26 06:03

Alan Geleynse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!