Collection, which method is used to authorize an add of an element?
We find a lot of concrete subclasses under Collection
.
Whil开发者_开发百科e trying to add an element in a concrete collection, this collection will use a method to determine if it can accept to store the element (and eventually that this element is not already in the collection).
It could use equals()
, hashCode()
or compareTo()
of the element.
Is it possible to find a summary about which method is used by each implementation of Collection
?
Thanks a lot for your answers.
First of all not all collections check whether the element you're adding already exists in the collection. For example ArrayList just appends the element to the tail of the list, without checking if it's already in the list. Other classes use equals if the collection is guaranteed to have only one copy of the object, or compareTo, if the elements are supposed to be Comparable and the collection is sorted (to find the right place to insert it at). Maps will also use equals to check for the key, but some like HashMap will also use hashCode() to speed up the searching process (they first get all keys with the same hashcode, and then use equals on each of them to find if the key already exists and has a value assigned, which will then get replaced).
But if you want to see how they work you can check out the sources that are included with the jdk. In eclipse I have the JRE set to the folder where the jdk is installed, and I can use CTRL+SHIFT+T to open any class (type) in the jdk, CTRL+click the name of a class, or for methods, even CTRL+click -> open implementation, which opens a pop up with the classes the implement that method (if it's from an interface, or the method directly in the class, if it's not)
Any concrete implementation should indicate in its API doc what assumptions it makes about the behaviour of its elements.
Generally, hash based collections use hashCode()
and tree based ones use compareTo()
or a Comparator
, and all of them use equals()
.
精彩评论