java Collections (Set, generic, Map, Collections)

catalogue

1.Set

1.1 Set overview and features

1.2 hash value

1.3 overview and characteristics of hshsset set

1.4 source code analysis of HashSet set to ensure element uniqueness

1.5 hash table of common data structures

1.6 LinkedHashSet set overview and features

1.7 overview and characteristics of TreeSet collection

1.8 use of natural sorting Comparable

1.9 use of Comparator sorting Comparator

2. Generics

2.1 generic overview

2.2 generic classes

2.3 generic methods

2.4 generic interfaces

2.5 type wildcards

2.6 variable parameters

2.7 use of variable parameters

3.Map

3.1 overview and use of map set

3.2 basic functions of map set

3.3 acquisition function of map set

3.4 traversal of map set (mode 1)

3.5 traversal of map set (mode 2)

4. Collections

4.1 Collections overview and usage

1.Set

1.1 Set overview and features

Set set features

  • A collection that does not contain duplicate elements
  • There is no indexed method, so you can't use a normal for loop to traverse
  • Iterative order random

example:

//HashSet: random iteration order
public class SetTest {
    public static void main(String[] args) {
        //Create collection object
        Set<String> set = new HashSet<String>();

        //Add element
        set.add("hello,world");
        set.add("hello,java");
        set.add("hello,python");
        set.add("hello,python");

        //ergodic
        for (String s :
                set) {
            System.out.println(s);
        }
    }
}

Console output:

1.2 hash value

Hash value: it is a value of Int type calculated by JDK according to the address, string or number of the object

There is a method in the Object class to get the hash value of the Object

  • public int hashCode(): returns the hash value of the object

Hash value characteristics of object

  • The hashCode() method is called multiple times for the same object, and the returned hash value is the same
  • By default, different objects have different hash values. Rewriting the hashCode() method can achieve the same hash value for different objects

example:

public class HashTest {
    public static void main(String[] args) {
        //Create student object
        Student student = new Student("lucycia",18,"man");

        //The hashCode() method is called multiple times for the same object, and the hash value returned is the same
        System.out.println(student.hashCode());//1769597131
        System.out.println(student.hashCode());//1769597131

        Student student2 = new Student("lucycia",18,"man");
        System.out.println("==============");
        //By default, different objects have different hash values
        //Through method rewriting, you can realize that the hash values of different objects are the same
        System.out.println(student2.hashCode());//1983747920

        System.out.println("==============");
        System.out.println("java".hashCode());//3254818
        System.out.println("python".hashCode());//-973197092
        System.out.println("html".hashCode());//3213227
        System.out.println("html".hashCode());//3213227

        System.out.println("==============");
        System.out.println("Heavily".hashCode());//1179395
        System.out.println("conversation".hashCode());//1179395
    }
}

Console output:

1.3 overview and characteristics of hshsset set

hashSet set characteristics

  • The underlying data structure is a hash table
  • The iterative order of the set is not guaranteed, that is, the order of stored and removed elements is not guaranteed
  • There is no indexed method, so you can't use a normal for loop to traverse
  • Because it is a Set set, it is a Set that does not contain duplicate elements

example:

public class HashSetTest {
    public static void main(String[] args) {
        //Create collection object
        Set<String> hs = new HashSet<String>();

        //Add element
        hs.add("hello,world");
        hs.add("hello,java");
        hs.add("hello,python");
        hs.add("hello,python");

        //ergodic
        for (String s :
                hs) {
            System.out.println(s);
        }
    }
}

Console output:

1.4 source code analysis of HashSet set to ensure element uniqueness

The process of adding an element to the HashSet collection

Set<String> hs = new HashSet<String>();

//Add element
hs.add("hello,world");
hs.add("hello,java");
hs.add("hello,python");
-----------------------------------------------

public boolean add(E e) {
    return map.put(e, PRESENT)==null;
}

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

//The hash value is calculated from the element's hashCode()
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //If the hash table is not initialized, it is initialized
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //The storage location of the object is calculated according to the hash value of the object. If there is no element in the location, the element is stored
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        /*
            The stored element compares the hash value with the previous element
            If the hash values are different, the execution continues down, adding elements to the collection
            If the hash values are the same, the object's equals () method is called for comparison
                If false is returned, the execution continues down, adding the element to the collection
                If true is returned, the element is repeated and no value is saved
        */
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

1.5 hash table of common data structures

Hashtable

  • Before JDK8, the bottom layer was implemented by array + linked list, which can be said to be an array with linked list elements
  • After JDK8, when the length is long, the bottom layer is optimized

1.6 LinkedHashSet set overview and features

LinkedHashSet set features

  • The Set interface implemented by hash table and linked list has an orderly iterative order
  • The order of elements is guaranteed by the linked list, that is, the storage and extraction order of elements are consistent
  • The hash table ensures that the elements are unique, that is, there are no duplicate elements

example:

public class LinkedHashSetTest {
    public static void main(String[] args) {
        //Create collection object
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();

        //Add element
        linkedHashSet.add("1");
        linkedHashSet.add("2");
        linkedHashSet.add("3");

        //Traversal object
        for (String s :
                linkedHashSet) {
            System.out.println(s);
        }
    }
}

Console output:

1.7 overview and characteristics of TreeSet collection

TreeSet set features

  • The elements are ordered. The order here does not refer to the order of storage and retrieval, but is sorted according to certain rules. The specific sorting method depends on the construction method
  • TreeSet(): sort according to the natural order of its elements
  • TreeSet (comparator): sort according to the specified comparator
  • There is no indexed method, so you can't use a normal for loop to traverse
  • A collection that does not contain duplicate elements because it is a Set collection

example:

public class TreeSetTest {
    public static void main(String[] args) {
        //Create collection object
        TreeSet<Integer> ts = new TreeSet<>();

        //Add element
        ts.add(1);
        ts.add(2);
        ts.add(3);
        ts.add(4);
        ts.add(5);

        //Ergodic combination
        for (Integer i :
                ts) {
            System.out.println(i);
        }
    }
}

Console output:

1.8 use of natural sorting Comparable

  • Store and traverse the student object, create a TreeSet collection, and use the parameterless construction method
  • Requirements: sort according to the age from small to large. If the age is the same, sort according to the alphabetical order of the name

Conclusion:

  • The TreeSet collection is used to store custom objects. The parameterless construction method uses natural sorting to sort elements
  • Natural sorting is to let the class to which the element belongs implement the Comparable interface and override the compareTo () method
  • When rewriting a method, be sure to note that the collation must be written according to the required primary and secondary conditions

example:

TreeSetTest2.java

public class TreeSetTest2 {
    public static void main(String[] args) {
        //Create collection object
        TreeSet<Student> ts = new TreeSet<>();

        //Create student object
        Student s1 = new Student("tom1",18,"man");
        Student s2 = new Student("tom2",28,"woman");
        Student s3 = new Student("tom3",38,"man");
        Student s4 = new Student("tom4",48,"woman");
        Student s5 = new Student("tom5",48,"woman");

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);

        for (Student s:
             ts) {
            System.out.println(s);
        }
    }
}

Student class

package com.lu.pojo;

public class Student implements Comparable<Student> {
    private String name;
    private int age;
    private String sex;

    public Student() {
    }

    public Student(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        if (name != null ? !name.equals(student.name) : student.name != null) return false;
        return sex != null ? sex.equals(student.sex) : student.sex == null;
    }

    @Override
    public int compareTo(Student o) {
        //return 0;
        //return 1;
        //return -1;
        //Sorted by age
        System.out.println(this.age + "   " + o.age);
        int num = this.age - o.age;
        //When the age is the same, sort alphabetically by name
        int num2 = num==0?this.name.compareTo(o.name):num;
        return num2;

    }
}

Console output:

1.9 use of Comparator sorting Comparator

Store the student object and traverse it, create a TreeSet collection, and use the construction method with parameters

Requirements: sort according to the age from small to large. If the age is the same, sort according to the alphabetical order of the name

example:

public class TreeSetTest3 {
    public static void main(String[] args) {
        TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s1.getAge() - s2.getAge();
                int num2 = num==0?s1.getName().compareTo(s2.getName()):num;
                return num2;
            }
        });

        //Create student object
        Student s1 = new Student("tom1",18,"man");
        Student s2 = new Student("tom2",10,"woman");
        Student s3 = new Student("tom3",38,"man");
        Student s4 = new Student("tom4",48,"woman");
        Student s5 = new Student("tom5",48,"woman");

        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);

        for (Student s:
                ts) {
            System.out.println(s);
        }
    }
}

Console output:

Conclusion:

  • The user-defined objects are stored in the TreeSet collection. The construction method with parameters uses comparator sorting to sort the elements
  • Comparator sorting is to let the collection construction method receive the implementation class object of comparator and override the compare() method
  • When rewriting a method, be sure to note that the collation must be written according to the required primary and secondary conditions

2. Generics

2.1 generic overview

Generic, or "parameterized type". When referring to parameters, the most familiar thing is that there is a formal parameter when defining the method, and then the arguments are passed when the method is called. So what about parameterized types? As the name suggests, it is to parameterize the type from the original specific type, which is similar to the variable parameters in the method. At this time, the type is also defined in the form of parameters (which can be called type parameters), and then the specific type (type arguments) is passed in during use / call.

This parameter type can be used in classes, methods and interfaces, which are called generic classes, generic methods and generic interfaces respectively.

Generic definition format:

  • < type >: Specifies the format of a type. The type here can be regarded as a formal parameter
  • < type 1, type 2... >: Specify mu lt iple types of formats separated by commas. The type here can be regarded as a formal parameter
  • In the future, the given type can be regarded as an argument, and the type of the argument can only be a reference data type

example:

/*
    Collection The collection stores the string and iterates through it
*/
public class GenericTest {
    public static void main(String[] args) {
        //Create collection object
        Collection<String> c = new ArrayList<String>();

        //Add element
        c.add("hello,java");
        c.add("hello,python");
        c.add("hello,html");
        c.add("100");

        Iterator<String> it = c.iterator();
        while (it.hasNext()) {
            String s = it.next();
            System.out.println(s);
        }
    }
}

Console output:

2.2 generic classes

Definition format of generic class:

  • Format: modifier class class name < type > {}
  • Example: public class generictest2 < T > {}

T here can be written as any identifier. Common parameters such as t, E, K and V are often used to represent generics

example:

Generic class

public class Generic<T> {
    private T t;

    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }
}

GenericTest3 class

public class GenericTest3 {
    public static void main(String[] args) {
        Generic<String> g = new Generic<>();
        g.setT("Zhou Xingchi");
        System.out.println(g.getT());

        Generic<Integer> g2 = new Generic<Integer>();
        g2.setT(55);
        System.out.println(g2.getT());
    }
}

Console output:

2.3 generic methods

Definition format of generic method:

Format: modifier < type > return value type method name (type variable name) {}

Example: public < T > void show (T) {}

example:

Generic class

//Generic method improvement
public class Generic {
    public <T> void show(T t) {
        System.out.println(t);
    }
}

GenericTest class

public class GenericTest {
    public static void main(String[] args) {
        Generic g = new Generic();
        g.show("Zhou Xingchi");
        g.show(55);
        g.show(true);
        g.show(12.33);
    }
}

Console output:

2.4 generic interfaces

Definition format of generic interface:

Format: modifier interface interface name < type > {}

Example: public interface generic < T > {}

example:

Generic interface

public interface Generic<T> {
    void show(T t);
}

GenericImpl implementation class

public class GenericImpl<T> implements Generic<T> {
    @Override
    public void show(T t) {
        System.out.println(t);
    }
}

GenericTest class

public class GenericTest {
    public static void main(String[] args) {
        Generic<String> g1 = new GenericImpl<String>();
        g1.show("Lin Qingxia");
        Generic<Integer> g2 = new GenericImpl<Integer>();
        g2.show(12);

    }
}

2.5 type wildcards

To represent the parent classes of various generic lists, you can use type wildcards

  • Type wildcard: <? >
  • List<?>: Represents a list whose element type is unknown, and its elements can match any type
  • This List with wildcards only indicates that it is the parent of various generic lists, and cannot add elements to it

If we don't want List <? > Is the parent class of any generic List. You only want it to represent the parent class of a generic List. You can use the upper limit of type wildcards

  • Upper limit of type wildcard: <? Extensions type >
  • List<? Extensions Number >: the type it represents is Number or its subclass

In addition to specifying the upper limit of type wildcards, we can also specify the lower limit of type wildcards

  • Type wildcard lower limit: <? super>
  • List<? Super Number >: the type it represents is Number or parent type

Example:

public class GenericTest {
    public static void main(String[] args) {
        //Type wildcard: <? >
        List<?> list1 = new ArrayList<Object>();
        List<?> list2 = new ArrayList<Number>();
        List<?> list3 = new ArrayList<Integer>();

        System.out.println("---------------");

        //Upper limit of type wildcard: <? Extensions type >
        //List<? extends Number> list4 = new ArrayList<Object>();
        List<? extends Number> list5 = new ArrayList<Number>();
        List<? extends Number> list6 = new ArrayList<Integer>();

        //Lower limit of type wildcard: <? Super type >
        List<? super Number> list7 = new ArrayList<Object>();
        List<? super Number> list8 = new ArrayList<Number>();
        //List<? super Number> list9 = new ArrayList<Integer>();
    }
}

2.6 variable parameters

Variable parameters are also called variable number of parameters. If they are used as formal parameters of a method, the number of method parameters is variable

  • Format: modifier return value type method name (data type... Variable name) {}
  • Example: public static int sum(int... a) {}

Variable parameter considerations

  • The variable here is actually an array
  • If a method has multiple parameters and contains variable parameters, the variable parameters should be placed later

example:

public class ArgsTest {
    public static void main(String[] args) {
        System.out.println(sum(10,10));
        System.out.println(sum(10,10,20));
        System.out.println(sum(10,10,20,20));
        System.out.println(sum(10,10,20,20,20));
        System.out.println(sum(10,10,20,20,20,20));
        System.out.println(sum(10,10,20,20,20,20,20));
        System.out.println(sum(10,10,20,20,20,20,20,20));
    }

    public static int sum(int... a) {
       int sum = 0;
        for (int i :
                a) {
            sum += i;
        }
        return sum;
    }

/*    public static int sum(int a, int b) {
        return a + b;
    }

    public static int sum(int a, int b, int c) {
        return a + b + c;
    }

    public static int sum(int a, int b, int c, int d) {
        return a + b + c + d;
    }*/
}

Console output:

2.7 use of variable parameters

There is a static method in the Arrays tool class:

  • Public static < T > List < T > aslist (t... A): returns a fixed size list supported by the specified array
  • The returned collection cannot be added or deleted, but can be modified

There is a static method in the List interface:

  • Public static < E > List < E > of (E... Elements): returns an immutable list containing any number of elements
  • The returned collection cannot be added, deleted or modified

There is a static method in the Set interface:

  • public static < E > set < E > of (E... Elements): returns an immutable combination containing any number of elements
  • When giving elements, you cannot give duplicate elements
  • The returned collection cannot be added or deleted. There is no modified method

example:

public class ArgsTest2 {
    public static void main(String[] args) {
        //Returns a list of fixed sizes supported by the specified array
        List<String> list = Arrays.asList("java", "python", "html");
        /*list.add("css");//UnsupportedOperationException*/
        /*list.remove("html");//UnsupportedOperationException*/
        list.set(1,"javascript");
        System.out.println(list);

        //Returns an immutable list containing any number of elements
        List<String> list2 = List.of("java", "python", "html", "html");
        /*list2.add("css");//UnsupportedOperationException*/
        /*list2.remove("html");//UnsupportedOperationException*/
        /*list2.set(1,"javascript");//UnsupportedOperationException*/
        System.out.println(list2);

        //Returns an immutable combination containing any number of elements
        /*Set<String> set = Set.of("java", "python", "html", "html");//IllegalArgumentException: duplicate element: html*/
        Set<String> set = Set.of("java", "python", "html");
/*        set.add("css");//UnsupportedOperationException
        set.remove("css");//UnsupportedOperationException*/
        System.out.println(set);
    }
}

Console output:

3.Map

3.1 overview and use of map set

Map collection overview

  • Interface map < K, V > k: type of key; 5: Type of value
  • Objects that map keys to values cannot contain duplicate keys, and each key can be mapped to at most one value
  • Example: student number and name

001 Stephen Chow

002 JDB

003 Andy Lau

Create an object for the Map collection

  • Polymorphic way
  • The specific implementation class is HashMap

example:

public class MapTest {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<String,String>();

        map.put("001", "Zhou Xingchi");
        map.put("002", "JDB");
        map.put("003", "Lau Andy");
        map.put("003", "Zhang Jiahui");

        System.out.println(map);
    }
}

Console output:

3.2 basic functions of map set

Method nameexplain
V put(K key, V value);
Add element
V remove(Object key)
Delete key value pair elements according to key
void clear()
Remove all key value pair elements
boolean containsKey(Object key)
Determines whether the collection contains the specified key
boolean containsValue(Object value)
Determines whether the collection contains the specified value
boolean isEmpty()
Determine whether the collection is empty
int size()The length of the set, that is, the number of key value pairs in the set

example:

public class MapTest2 {
    public static void main(String[] args) {
        //Create collection object
        Map<String, String> map = new HashMap<>();

        //Add collection element
        map.put("001", "Zhou Xingchi");
        map.put("002", "JDB");
        map.put("003", "Lau Andy");
        System.out.println(map);

        //Delete key value pair elements according to key
        System.out.println(map.remove("001"));
        System.out.println(map);

        //Determines whether the collection contains the specified key
        System.out.println(map.containsKey("002"));

        //Determines whether the collection contains the specified value
        System.out.println(map.containsValue("JDB"));

        //Determine whether the collection is empty
        System.out.println(map.isEmpty());

        //The length of the set, that is, the number of key value pairs in the set
        System.out.println(map.size());

        //Remove all key value pair elements
        map.clear();
        System.out.println(map);

    }
}

Console output:

3.3 acquisition function of map set

Method nameexplain
V get(Object key)
Get value according to key
Set<K> keySet()
Gets a collection of all keys
Collection<V> values()
Gets a collection of all values
Set<Map.Entry<K, V>> entrySet()
Gets a collection of all key value pair objects

example:

/*
V get(Object key)	Get value according to key
Set<K> keySet()	Gets a collection of all keys
Collection<V> values()	Gets a collection of all values
Set<Map.Entry<K, V>> entrySet()	Gets a collection of all key value pair objects
 */

public class MapTest3 {
    public static void main(String[] args) {
        //Create collection object
        Map<String, String> map = new HashMap<>();

        //Add collection element
        map.put("Sing ", "Zhou Xingchi");
        map.put("007", "JDB");
        map.put("Huazi", "Lau Andy");
        System.out.println(map);

        //V get(Object key) 	 Get value according to key
        System.out.println("=====================");
        System.out.println(map.get("Sing "));

        //Set<K> keySet() 	 Gets a collection of all keys
        System.out.println("=====================");
        System.out.println(map.keySet());
        System.out.println("=====================");
        Set<String> keySet = map.keySet();
        for (String s :
                keySet) {
            System.out.println(s);
        }


        //Collection<V> values() 	 Gets a collection of all values
        System.out.println("=====================");
        System.out.println(map.values());

        //Set<Map. Entry<K, V>> entrySet() 	 Gets a collection of all key value pair objects
        System.out.println("=====================");
        System.out.println(map.entrySet());
    }
}

Console output:

3.4 traversal of map set (mode 1)

  • First, get all the key sets of the map set
  • Save the key set in the set, and then iterate through the get method of map

example:

public class MapTest {
    public static void main(String[] args) {
        //Create collection object
        Map<String, String> map = new HashMap<>();

        //Add collection element
        map.put("Sing ", "Zhou Xingchi");
        map.put("007", "JDB");
        map.put("Huazi", "Lau Andy");
        System.out.println(map);

        Set<String> set = map.keySet();
        for (String s :
                set) {
            System.out.println(map.get(s));
        }
    }
}

Console output:

3.5 traversal of map set (mode 2)

  • First, get the collection of all key value pair objects
  • Then traverse each key value pair object
  • Get keys and values for objects based on key values

example:

public class MapTest2 {
    public static void main(String[] args) {
        //Create collection object
        Map<String, String> map = new HashMap<>();

        //Add collection element
        map.put("Sing ", "Zhou Xingchi");
        map.put("007", "JDB");
        map.put("Huazi", "Lau Andy");
        System.out.println(map);
        
        //Gets a collection of all key value pair objects
        Set<Map.Entry<String, String>> entrySet = map.entrySet();
        
        //Traverse the collection of key value pair objects to get each key value pair object
        for (Map.Entry<String, String> me :
                entrySet) {
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(key + "  " + value);
        }
    }
}

Console output:

4. Collections

4.1 Collections overview and usage

Overview of the Collections class

  • Is a tool class for collection operations

Common methods of Collections class

Method nameexplain
public static <T extends Comparable<? super T>> void sort(List<T> list)
Sorts the specified list in ascending order
public static void reverse(List<?> list)
Reverses the order of the elements in the specified list
public static void shuffle(List<?> list)
Randomly arranges the specified list using the default random elements

Example:

public class CollectionsTest {
    public static void main(String[] args) {
        //Create collection object
        List<Integer> list = new ArrayList<>();

        //Add element
        list.add(60);
        list.add(20);
        list.add(10);
        list.add(40);
        list.add(50);

        System.out.println(list);

        //public static <T extends Comparable<? super T>> void sort(List<T> list)
        Collections.sort(list);
        System.out.println(list);

        //public static void reverse(List<?> list)
        Collections.reverse(list);
        System.out.println(list);

        //public static void shuffle(List<?> list)
        Collections.shuffle(list);
        System.out.println(list);
    }
}

Console output:

Keywords: Java

Added by invinate on Mon, 03 Jan 2022 04:18:42 +0200