Convert Set<Object> to Collection<String>
21,153
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.
Comments
-
MightyPork almost 4 years
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?
-
MightyPork almost 10 yearsSorry I wasn't clear enough. Check if the answer is still valid for what I really am doing.
-
StriplingWarrior almost 10 years@MightyPork: Yes, the answer is still valid. Since you don't have to do any specific steps for conversion (you're just casting
Object
s toString
s), you can achieve the same end by casting the collection itself. -
MightyPork almost 10 yearsNo good, I tried
return (Set<String>) props.keySet();
but it said ICannot cast from Set<Object> to Set<String>
. -
StriplingWarrior almost 10 years@MightyPork: Try my update. I've been away from java for too long.
-
MightyPork almost 10 yearsOkay now this at least compiles. I'll have to fix a lot more code before I can try if it actually works. It's "Unchecked" though - is that okay?
-
StriplingWarrior almost 10 years@MightyPork: I don't know enough about your code to be able to tell you whether this is "okay." I'd personally question why
props
isn't cast to the right type in the first place--that would give you better type safety, and avoid the need for this kind of hack. Your original code would have the advantage of "failing fast" if any objects in the keySet are not strings, but you're the one who says you know they'll always be strings. -
Stuart Marks almost 10 years@MightyPork Add
@SuppressWarnings("unchecked")
before this line and it will shut off the warning. Of course, only do this if you are sure the contents are all strings.