Set and Map

catalogue

 

HashSet

hashcode method:

equals method:

comparator

1. Internal comparator

External comparator

1. Define a class that implements the interface

2. Use anonymous inner class----

3. Use Lmabda expression

HashMap

HashSet

Underlying structure: hash table (array + linked list + red black tree) ------------ > maintained by HashMap

Advantages: it integrates array, linked list and red black tree, so it has good comprehensive ability and high efficiency of query, addition and deletion

Disadvantages: it implements the Set interface, so it is out of order

Application scenario: to store different data, it is recommended to use HashSet when the efficiency of query, addition and deletion is high

No new interface

De duplication: override hashcode and equals methods in the custom reference data types that need to be stored

hashcode method:

    //Store Person object
    hash.add(new Person("Zhang San",18));
    hash.add(new Person("Li Si",17));
    hash.add(new Person("Zhang San",18));
​
    System.out.println(hash);
    System.out.println(new Person("Zhang San",18).hashCode());
    System.out.println(new Person("Zhang San",18).hashCode());
}
    

equals method:

//Omit constructor, set/get method, toString method
//Rewrite equals and hashCode
@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    Student student = (Student) o;
    return age == student.age &&
            Objects.equals(name, student.name);
}
@Override
public int hashCode() {
    return Objects.hash(name, age);
}

comparator

1. Internal comparator

Also known as natural sorting, it is a comparison method defined within a type and implements Java Lang. comparable interface

Usage: implement the Comparable interface and rewrite the compareTo(T o) method

Method specifies the comparison rule internally: compareTo return value int type T1 compareTo (T2) - > 0: equal integer: T1 > T2 negative number: T1 < T2

Advantages and disadvantages:

Advantages: the default comparison method is defined inside the class

Disadvantages: fixed, hard coded, not flexible enough

Code: take the Person above as an example

Class person implements comparable < person > {............ / / rewrite the compareTo method. Take age as an example, public int compareTo (student o) {return this. Getage. - o.getage();}}

External comparator

Also known as customized sorting, it is a comparison method defined outside a type (the type of object data to be compared)

Usage: implement Java util. Comparator < T > interface, rewrite compare(T t1, T t2)

Return value of defined comparison rule: 0: equal positive number: T1 > T2 negative number: T1 < T2

//Three ways

1. Define a class that implements the interface

Class demo implements comparator < person > {@ override public int compare (person O1, person O2) {/ / return O2. Getage() - O1. Getage(); use age comparison return o1.getName().compareTo(o2.getName()); / / use name comparison}}

2. Use anonymous inner class----

---->Simplify the implementation class comparator < person > com = new comparator < person > () {@ override public int compare (person O1, person O2) {return O1. Getage() - O2. Getage();}};

3. Use Lmabda expression

com = (x,y)->y.getAge()-x.getAge(); Arrays. Sort (array) is sorted in ascending order by default,

Use arrays Sort (array) compares arrays of custom reference data types

A comparator is required for comparison

public static void main(String[] args) {
    //array
    Person[] arr = {
        new Person("zhangsan",18),
        new Person("lisa",16),
        new Person("wangwu",19),
        new Person("Zhao Liu",19)
    };
​
    System.out.println(Arrays.toString(arr));
    //Use the compareTo method in the Person class of the default comparison rule
    Arrays.sort(arr);
    //Use the external comparison rule specified by parameter 2
    Arrays.sort(arr, (t1,t2)->t1.getAge()-t2.getAge());
    System.out.println(Arrays.toString(arr));
}

The elements in the map < K, V > set are composed of key value pairs k-v (key): it can be any reference data type data -- > set disordered and non repeatable v(value): it can be any reference data type data -- > collection repeatable and disordered. A key can only correspond to one value - > the mapping relationship can operate value according to the key. The disorder and de duplication of the map are determined by the key

Some common methods of Map collection: public static void main(String[] args) {/ / create a Map collection Map < integer, string > Map = new HashMap < > ();

V put(K key, V value) Optionally, associate the specified value with the specified key in this mapping.
V get(Object key) Returns the value to which the specified key is mapped, or if the mapping does not contain a key mapping null . 
boolean containsKey(Object key) Returns if this mapping contains a mapping for the specified key true . 
boolean containsValue(Object value) Returns if the mapping maps one or more keys to the specified value true . 
V remove(Object key) Optionally, remove the key's mapping from the mapping if it exists.

The traversal method of the map set is keySet, which obtains all key values, returns a set values() to obtain the values of all key value pairs in the map set, and returns a Collection entrySet() to obtain all key value pairs - > map Entry type - > indicates a key value pair public static void main(String[] args) {/ / create a map set map < integer, string > map = new HashMap < > (); map.put (1001, "Zhangsan"); map.put (1002, "Lisi"); map.put (1003, "Wangwu");

//1.keySet
Set<Integer> keys= map.keySet();
for(Integer i:keys){
    System.out.println(i+"-->"+map.get(i));
}
​
//2.values()
Collection<String> col = map.values();
for(String s:col){
    System.out.println(s);
}
​
//3)entrySet
Set<Map.Entry<Integer,String>> set = map.entrySet();
Iterator<Map.Entry<Integer,String>> it = set.iterator();
for(;it.hasNext();){
    Map.Entry entry = it.next();
    System.out.println(entry.getKey()+"-->"+entry.getValue());
}
}

HashMap

Underlying structure: hash table (array + linked list + red black tree)

Features: query, high efficiency of addition and deletion

New content: no new function

Traversal method: the same as the Map interface

Capacity expansion: the initial capacity is 16, newcap = oldcap < < 1, and the array is expanded twice the original capacity each time

DEFAULT_ INITIAL_ Capability initial capacity 16

DEFAULT_LOAD_FACTOR: the default loading factor is 0.75

threshold: expansion critical value DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY

Keywords: Java

Added by dreams4000 on Sat, 29 Jan 2022 02:21:21 +0200