[英]Why doesn't the JDK Collections.distinct enforce that the parameters contain the same element type?
该方法的javadoc 。
我希望以下代码导致类型错误:
List<String> ls = new ArrayList<>();
List<Integer> li = new ArrayList<>();
boolean result = Collections.disjoint(ls, li);
然而,事实并非如此,它将永远返回true。 为什么要允许它?
我看不出有什么奇怪的。 考虑一下Java之间的相等性是在对象之间表达的事实,您拥有boolean equals(Object other)
而不是boolean equals(T other)
。
由于确实使用了equals
来查找两个集合是否不相交(如果是集合,则为hashCode()
),为什么还要引发类型错误?
按照这种观点,即使
Set<Integer> set = new HashSet<Integer>();
boolean test = set.contains("foobar");
应该被认为是错误。
我不知道该决定背后的确切原因。 但是,它允许一些非常有用的行为,例如比较一组Foo
和一组Bar extends Foo
的不相交性。 通配符类型是允许这样做的方法。
这是一个更好的问题:为什么会这样?
考虑Foo extends Bar
, Bar extends Jo
, Blo extends Jo
,然后:
List<Jo> jos = new ArrayList<Jo>();
List<Bar> bars = new ArrayList<Bar>();
//populate both lists arbitrarily
Collections.disjoint(jos, bars);
上面的调用是完全有效的,可以返回true
或false
,为什么要阻止它呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.