为什么 java.util.Set 不能从 java.lang.Iterable 进行赋值?

huangapple go评论64阅读模式
英文:

Why is java.util.Set not Assignable From java.lang.Iterable?

问题

当我调用Set.class.isAssignableFrom(Iterable.class)时,它返回false

然而,在文档中,java.util.Set被列为java.lang.Iterable的子接口。因此我感到困惑。你甚至可以尝试在一行代码中测试:

System.out.println(Set.class.getName() + " is " + ((Set.class.isAssignableFrom(Iterable.class)) ? "" : "NOT ") + "assignable from " + Iterable.class.getName());

它会打印出java.util.Set is NOT assignable from java.lang.Iterable

为什么会这样呢?

英文:

When I call Set.class.isAssignableFrom(Iterable.class), it returns false.

Nevertheless, in the docs, java.util.Set is listed as a subinterface of java.lang.Iterable. Hence my confusion. You can even try it out in a single line of code:

System.out.println(Set.class.getName() + " is " + ((Set.class.isAssignableFrom(Iterable.class)) ? "" : "NOT " ) + "assignable from " + Iterable.class.getName());

it prints java.util.Set is NOT assignable from java.lang.Iterable.

Why is that?

答案1

得分: 3

因为你错误地使用了 isAssignableFrom

正如文档所述,isAssignableFrom(Class<?> cls) "确定由此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是指定的Class参数的超类或超接口"。所以 cls 应该是 Set.class,完整的语法是:

Iterable.class.isAssignableFrom(Set.class)

...确实会返回 true

英文:

That's because you're using isAssignableFrom wrong.

As the docs say, isAssignableFrom(Class&lt;?&gt; cls) "determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter". So cls would be Set.class, and the full syntax would be:

Iterable.class.isAssignableFrom(Set.class).

...which, indeed, returns true.

huangapple
  • 本文由 发表于 2020年10月10日 19:48:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64293083.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定