HashSet cannot be converted to String error with instanceof 运算符

HashSet cannot be converted to String error with instanceof operator

我有这些嵌套的哈希集,其中内部包含 String 个值。

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

在我的代码中的某个时刻,我不知道我是在处理内部哈希集还是外部哈希集。我试图通过使用以下代码行来确定:

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

这行代码似乎产生了一个错误:

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

loopIterator3确实遍历内部哈希集时,我希望 它将采用 String 值。为什么编译器认为它是一个哈希集? 此外,为什么编译器认为我正在尝试转换?

任何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));
    }
}

这个错误是因为HashSetString不相关。我看到您已经知道 next() 方法返回的对象类型。我不明白目的。不过,如果您需要此检查,请尝试以下操作-

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

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

来源:- https://docs.oracle.com/javase/specs/jls/se7/jls7.pdf(第 513 页)

例如 a instanceof B(a 是 class A 的对象),如果 A 和 B 不在同一层次结构中,即它们不是 subclass 或 superclass 要么这是编译时错误,因为如果它们不在同一层次结构中,那么 a 不可能是 instanceof B。因此编译器在编译时显示错误。

在你的例子中,HashSet 不是 String 的子class 或 superclass,反之亦然,因此它显示编译时错误