equals()方法注意事项

Collection (Java 2 Platform SE 5.0) <script type="text/javascript"> function windowTitle() { parent.document.title="Collection (Java 2 Platform SE 5.0)"; } </script> <noscript></noscript> <script src="/jdk150/H2HHinclude.js"></script>

equals

boolean equals
(Object
 o)
Compares the specified object with this collection for equality.

While the Collection interface adds no stipulations to the general contract for the Object.equals , programmers who implement the Collection interface "directly" (in other words, create a class that is a Collection but is not a Set or a List ) must exercise care if they choose to override the Object.equals . It is not necessary to do so, and the simplest course of action is to rely on Object 's implementation, but the implementer may wish to implement a "value comparison" in place of the default "reference comparison." (The List and Set interfaces mandate such value comparisons.)

The general contract for the Object.equals method states that equals must be symmetric (in other words, a.equals(b) if and only if b.equals(a) ). The contracts for List.equals and Set.equals state that lists are only equal to other lists, and sets to other sets . Thus, a custom equals method for a collection class that implements neither the List nor Set interface must return false when this collection is compared to any list or set. (By the same logic, it is not possible to write a class that correctly implements both the Set and List interfaces.)

用equals()进行两个对象的比较时,对象的类型必须一致.如List.euqals()返回true当且仅当比较的两个对象同为List.这也解释了Thinking in java(第四版中文版)中223页的这几行代码:

Pet cymric = new Cymric();
System.out.println("5: " + pets.indexOf(cymric));
System.out.println("6: " + pets.remove(cymric));
由于indexOf(),cotains(),remove()方法都需要用到equals(),尽管List<Pet>pets已经包含了crymric,但用新建的Crymric对象crymric作为indexOf()和remove()的参数都不会得到我们希望的结果,因为crymric不是List对象.

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值