Convert Set<Object> to Collection<String>

21,153

If you know that all the Objects 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.

Share:
21,153
MightyPork
Author by

MightyPork

doing some web development and embedded hacking in C

Updated on July 27, 2020

Comments

  • MightyPork
    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
    MightyPork almost 10 years
    Sorry I wasn't clear enough. Check if the answer is still valid for what I really am doing.
  • StriplingWarrior
    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 Objects to Strings), you can achieve the same end by casting the collection itself.
  • MightyPork
    MightyPork almost 10 years
    No good, I tried return (Set<String>) props.keySet(); but it said I Cannot cast from Set<Object> to Set<String>.
  • StriplingWarrior
    StriplingWarrior almost 10 years
    @MightyPork: Try my update. I've been away from java for too long.
  • MightyPork
    MightyPork almost 10 years
    Okay 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
    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
    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.