简体   繁体   中英

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?

The latter will throw a ClassCastException if the original Set wasn't a HashSet .

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.

The primary difference is that new creates a new object, but a type cast doesn't.

Consider the following example:

HashSet<Integer> one = ...

HashSet<Integer> two = new HashSet<Integer>(one);
HashSet<Integer> three = (HashSet<Integer>) one;

System.out.println(one == two);  // Prints false
System.out.println(one == three);  // Prints true

In other words, one refers to the same object as three , but two refers to a different object.

Apart from the different result from == , you will find that updates to the set referred to by one will be visible via three but not via two .


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

The reason you don't see it used much is because the second option does NOT create a new object!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM