What is the difference between type casting a set to HashSet and initializing a HashSet with a set?

I am looking to convert a set values (from Collectors.toSet()) into a HashSet, what is the difference between these two and which is generally preferred?

HashSet<Integer> set = new HashSet<Integer>(values);
HashSet<Integer> set = (HashSet<Integer>) values;

I don’t see the second option used as much, but wouldn’t it be faster to cast than creating a new object?


You’re not casting a set anywhere here. Set is an interface which means it can’t be instantiated (classes that implement set can be instantiated). What this means is that your variable values need an implementation such as a hashset. So, option two only works if already instantiated some sort of set, which would be slower(more verbose is what I think you mean). Like this:

Set<Integer> = new HashSet<Integer> values;
HashSet<Integer> set = (HashSet<Integer>) values. 

It’s likely no one is going to do something like this in the first place, it makes more sense to stick with just plain old making a hashet:

HashSet<Integer> set = new HashSet<Integer>();

You may also be thinking that its ok to do without an implementation like :

1 Set<Integer> values; 
2 HashSet<Integer> set = (HashSet<Integer>) values;

Since in line 1 we can create a variable of the Set interface (keep in mind no actual object) this line is ok. But without an implementation there would be no point in casting at line 2.

To sum it up, this question doesn’t make too much sense in the first place. Cast where you actually need to cast.

Leave a Reply

Your email address will not be published. Required fields are marked *