The collection class for Java is divided into two types, collection and map,collection are also set and list.
1. Whether the elements in the collection class are the same
HashSet uses equals and hashcode two functions together to determine
TreeSet using CompareTo in the comparable interface, or compare functions in comparator
ArrayList using the Equals function
The key in HashMap is the same as HashSet, and value uses the Equals function
The key in TreeMap is the same as TreeSet, and value uses the Equals function
2. Whether the collection can contain null, or duplicate elements
HashSet can contain null, cannot contain duplicate elements
TreeSet with HashSet, can contain a null, adding a second null throws an exception
ArrayList can contain null, or it can contain duplicate elements
The key in HashMap is the same as hashset, and value can contain more than one null
The key in TreeMap is the same as TreeSet, and value can contain more than one null
3. About the contains and remove functions
Hashset,treeset,arraylist can use the following function to determine whether to include an element, or to delete an element
Boolean contains (Object o)
Boolean remove (Object o)
Hashmap,treemap has the following functions:
Boolean ContainsKey (Object key)
Boolean containsvalue (Object key)
Boolean remove (Object key)
In the implementation of these functions, you need to call the Equals method, so is the Equals method that invokes the parameter (with the element in the collection as the equals function argument) or the Equals method of each element?
The answer is the Equals method that invokes the parameter. Take the implementation of the Remove method as an example
- Public boolean remove (Object o) {
- if (o == null ) {
- for ( span class= "keyword" style= "Color:rgb (127,0,85); Font-weight:bold ">int index = 0 ; index < size; index++)
- if (Elementdata[index] = = null) {
- Fastremove (index);
- return true;
- }
- } else {
- < span class= "keyword" style= "Color:rgb (127,0,85); Font-weight:bold ">for (int index = 0 ; index < size; index++)
- if (O.equals(Elementdata[index])) {
- Fastremove (index);
- return true;
- }
- }
- return false;
- }
4. collection classes and Arrays
The collection class collection has the object[] ToArray () function, which is used to convert the collection to an array.
The Arrays tool class provides a aslist (Object ... a) method for converting an array to ArrayList, noting that this is the inner class of the arrays class and also inherits from list, which is fixed in length and differs from previous ArrayList.
Java Collection Class Learning summary