Reputation: 18901
I have a Set<Object>
.
I need to get a Collection<String>
from it.
I can think of making a for loop to add and cast all the Objects, but that is ugly and probably also slow.
@Override
public Collection<String> keys()
{
// props is based on HashMap
Set<String> keys = new HashSet<>();
for (Object o : props.keySet()) {
keys.add((String) o);
}
return keys;
}
What is the right way?
Upvotes: 15
Views: 28554
Reputation: 156748
If you know that all the Object
s inside the HashSet
are strings, you can just cast it:
Collection<String> set = (Collection<String>)(Collection<?>)props.keySet();
Java implements generics with erasure, meaning that the HashSet itself doesn't know at runtime that it's a HashSet<Object>
--it just knows it's a HashSet
, and the compiler is responsible for helping programmers to avoid doing things that would create runtime exceptions. But if you know what you're doing, the compiler won't prevent you from doing this cast.
Upvotes: 14