Search code examples
javahashsetinstanceof

HashSet cannot be converted to String error with instanceof operator


I have these nested hashsets, in which the inner contain String values.

{{a,b},{b,c},{c,e}}

At one point in my code, I do not know whether I am dealing with the inner hashset or the outer one. I am trying to ascertain by using the following line of code:

System.out.println(loopIterator3.next() instanceof String);
 //(FYI :Iterator <HashSet> loopIterator3 = hsConc2.iterator();)

This line of code seems to generate an error:

prog.java:61: error: incompatible types: HashSet cannot be converted to String System.out.println(loopIterator3.next() instanceof String);

When loopIterator3 is indeed traversing an inner hashset, i would expect it would be taking String values. Why does the compiler think it is a hashset? Moreover, why does the compiler think I am trying to convert?

Any thoughts/suggestions?

import java.util.Arrays;
import java.util.HashSet;

class Scratch {
    public static void main(String[] args) {
        HashSet<HashSet<String>> hashSets = new HashSet<>(Arrays.asList(newSet("a", "b"), newSet("b", "c"), newSet("c", "e")));

        System.out.println(hashSets.iterator().next() instanceof String); //error
        System.out.println(hashSets.iterator().next().iterator().next() instanceof String);
    }

    private static HashSet<String> newSet(String... str) {
        return new HashSet<>(Arrays.asList(str));
    }
}

Solution

  • This error is because HashSet and String are not related. I see that you already know the type of object returned by next() method. I did not understand the purpose. Still if you need this check, try something like below-

    Object obj = loopIterator3.next();
    String.class.isInstance(obj);