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