java contains多个参数,为什么List.contains()将Object作为Collections Java中的参数

The java.util.List.contains(Object o) method takes Object as an argument and internally uses Object.equals(Object o) as described here.

If I do the following code in Netbeans:

List listStr = new ArrayList<>();

listStr.contains(34); //warning

it gives the obvious warning, that is:

Given object can not contain instances of int (expected String)

Since it visible to all, that String never be equal to int then why shouldn't it take Element type E (in my case String) as an argument instead of Object?

解决方案

Strictly speaking such an implementation would be wrong.

The reason for this is that even if an object is not of type E, it could still return true on an equals() call.

Assume for a second, that you've got a class like this:

public class FakeString {

private final String value;

public FakeString(String value) {

if (value == null) {

throw new IllegalArgumentException();

}

this.value = value;

}

public int hashCode() {

return value.hashCode();

}

public boolean equals(Object o) {

return value.equals(o);

}

}

Then this code would print true:

List strings = Arrays.asList("foo", "bar", "baz");

System.out.println(strings.contains(new FakeString("bar")));

And just to clarify: this behaviour is intended and is the reason why contains() takes an Object instead of E. The same is true for remove(), by the way.

Your int will be boxed to an Object.

(int) === boxing ===> (Integer) ==== reference widening ===> (Object)

But Netbeans is smart and detects this, notices that your Integer is incompatible with a String. Normally this would throw a ClassCastException. However, the javadoc clearly states that throwing the ClassCastException on Collections.contains(Object) is optional.

So in this case, there would be no benefit to overload the contains method to allow an Element type because int, float, double, etc can be autoboxed to Object successfully. Therefore, a contains with just Object is just fine.

For reasons unknown, List, HashSet, Set, and LinkedHashSet do not throw a ClassCastException if "f the type of the specified element is incompatible with this [insert type here] (optional)". Note the optional part. As you have shown, Netbeans will give you a suspicious warning when you try to pass an incompatible type. The trap here is if you try to use logic to rely on the return value of .contains(...). A developer who doesn't pay attention to his warnings could fall into the trap of assuming that contains will always work, but then it doesn't.

As the developer at this blog recommends, here are four steps to avoid this pitfall in the future:

Careful coding and code reviews might lead to developers or reviewers seeing that an object of an irrelevant class is being passed

to the contains method. I'm typically uncomfortable leaving it with

just this form of protection.

Use of a modern version of NetBeans or of similar tools that flag the "suspicious" behavior can be very helpful.

Unit tests combined with code coverage tests can be helpful in identifying seemingly strange flows through the code that can be

attributed to issues such as the one described in this post.

Collection implementations that do throw ClassCastException at least provide a runtime error to let developers know that an improper

action is being taken. It may not be as effective as compile-time

detection, but it does make it much easier to identify that there is a

problem and what it is when it happens then without it. However, the

major disadvantage with this approach is that the choice of which

collection implementation to use is often driven by important

considerations that often outweigh the desire to have runtime

detection of an errant call to contains.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值