Java collections and generics

Posted by rptasiuk on Sat, 25 Dec 2021 06:41:55 +0100

Java collections and generics (dark horse programmer)

1,Collection

1.1 review of collective knowledge

Features of collection class: it provides a storage model with variable storage space, and the number of storage containers will change at any time

1.2. Set class architecture

1.3 Collection overview and usage

Collection collection overview

  • Is the top-level interface of a singleton Collection. It represents a set of objects, which are also called Collection elements
  • JDK does not provide any direct implementation of this interface. It provides more specific implementation of sub interfaces (such as Set and List)

Create an object for the Collection

  • Polymorphic way
  • The specific implementation class is ArraryList
import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo1 {
    public static void main(String[] args) {
        //Create an object for the collection collection
        Collection<String> c = new ArrayList<String>();
        //Add element, Boolean add (E)
        c.add("hello");
        c.add("my");
        c.add("dp");

        //Output collection object
        System.out.println(c);//The result is [hello, my, dp]

    }
}

1.4 common methods of Collection

/*
    Collection Common methods of collection:
        boolean add(E e)Add element
        boolean remove(Object o) Removes the specified element from the collection
        void clear()    Empty elements in collection
        boolean contains(Object o)  Determines whether the specified element exists in the collection
        boolean isEmpty()   Determine whether the collection is empty
        int size()     The length of the set, that is, the number of elements in the set
 */

import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo2 {

    public static void main(String[] args) {
        //Create collection object
        Collection<String> c = new ArrayList<String>();
        //Boolean add (E) add element
        c.add("hello");
        c.add("my");
        c.add("dp");
        //Output collection object
        System.out.println(c);//[hello, my, dp]

        //boolean remove(Object o) removes the specified element from the collection
//        c.remove("my");
//        System.out.println(c);//[hello, dp]

        //void clear() clears the elements in the collection
//        c.clear();
//        System.out.println(c);//[]

        //boolean contains(Object o) determines whether the specified element exists in the collection
        System.out.println(c.contains("dp"));//true
        System.out.println(c.contains("1"));//false

        //boolean isEmpty() determines whether the collection is empty
        System.out.println(c.isEmpty());//false

        //int size() the length of the set, that is, the number of elements in the set
        System.out.println(c.size());//3
    }
}

1.5 traversal of Collection

Iterator: iterator, a special traversal mode of a collection

  • Iterator iterator(): returns the iterator of the elements in this collection, which is obtained through the iiiterator () method of the collection
  • The iterator is obtained through the iterator() method of the collection, so we say that it depends on the existence of the collection

Common methods in Iterator

  • E next(): returns the next element in the iteration
  • boolean hasNext(): returns true if the iteration has more elements
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Iterator iterator  {
    public static void main(String[] args) {
        //Create collection object
        Collection<String> c = new ArrayList<String>();

        //Add element
        c.add("hello");
        c.add("my");
        c.add("dp");

        //Iterator < E > iterator(): returns the iterator of the elements in this collection, which is obtained through the iiiterator() method of the collection
        Iterator<String> it = c.iterator();

        //ergodic
        while (it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }
    }
}

1.6 use steps of collection

2,List

2.1 List set overview and features

List collection overview

  • An ordered set (also known as a sequence), where users can precisely control the insertion position of each element in the list. Users can access elements through integer indexes and search for elements in the list
  • Unlike set collections, lists usually allow duplicate elements

List set features:

  • Ordered: the stored and retrieved elements are in the same order
  • Repeatable: stored elements can be repeated
/*
    list Set characteristics
        * ==Ordered = =: the stored and retrieved elements are in the same order
        * ==Repeatable = =: stored elements can be repeated
 */

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

        //Add element
        list.add("hello");
        list.add("my");
        list.add("dp");
        list.add("my");

        //Output collection object
        System.out.println(list);//[hello, my, dp, my]

        System.out.println("-----------");
        
        //Iterator traversal
        Iterator<String> it = list.iterator();
        while (it.hasNext()){
            String s = it.next();
            System.out.println(s);
        }

    }
}

2.3. List set specific methods

import java.util.ArrayList;
import java.util.List;

/*
    list Collection specific methods:
        void add(int index,E element)   Inserts the specified element at the specified location in this collection
        E remove(int index)     Deletes the element at the specified index and returns the deleted element
        E set(int index,E element)  Modify the element at the specified index and return the modified element
        E get(int index)      Returns the element at the specified index
 */

public class ListDemo2 {

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

        //Add element
        list.add("hello");
        list.add("my");
        list.add("dp");

        // void add(int index,E element) inserts the specified element at the specified position in this collection
        list.add(1,"hh");
        System.out.println(list);//[hello, hh, my, dp]

        // E remove(int index) deletes the element at the specified index and returns the deleted element
        list.remove("my");
        System.out.println(list);//[hello, hh, dp]

        // E set(int index,E element) modifies the element at the specified index and returns the modified element
        list.set(1,"java");
        System.out.println(list);//[hello, java, dp]

        //E get(int index) returns the element at the specified index
        System.out.println(list.get(1));//java

        //Use the for loop to traverse
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            System.out.println(s);
        }

    }
}

list stores a collection of student objects

/*
    Requirements: create a collection for storing student objects, store 3 student objects, and use the program to traverse the collection on the console
    Idea:
        1.Define student classes
        2.Create a list collection object
        3.Create student object
        4.Add students to collection
        5.Traversing a collection (iterator mode, for loop mode)
 */

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo {

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

        //Create student object
        Student s1 = new Student("Dapeng",3);
        Student s2 = new Student("Xiao Ming",3);
        Student s3 = new Student("Xiao Hong",3);

        //Add students to collection
        list.add(s1);
        list.add(s2);
        list.add(s3);

        //Iterator pattern 
        Iterator<Student> it = list.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName()+","+s.getAge());
        }
        System.out.println("---------");

        //for loop
        for (int i = 0; i <list.size() ; i++) {
            Student s = list.get(i);
            System.out.println(s.getName()+","+s.getAge());
        }

    }
}

2.4. Concurrent modification exception

/*
    Requirements:
        I have a set, list < string > List = new ArrayList < string > ()
        There are three elements: list add("hello");
                        list.add("my");
                        list.add("dp");
        Traverse the collection to get each element. See if there is a "dp" element. If so, I will add a "java world" element. Please write code to implement it

     ConcurrentModificationException: When such modification is not allowed, this exception can be thrown by detecting the concurrent modification of the object
 */


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

        //Add element
        list.add("hello");
        list.add("my");
        list.add("dp");

        //Traverse the collection to get each element. See if there is a "dp" element. If so, I will add a "java world" element. Please write code to implement it
//        Iterator<String> it = list.iterator();
//        while (it.hasNext()){
//            String s = it.next();
//            if (s.equals("dp")){
//                list.add("java world");
//            }
//        }//This will result in an error, ConcurrentModificationException

        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            if (s.equals("dp")){
                list.add("java world");
                System.out.println(list);
            }
        }

    }
}

2.5,ListIterator

ListIterator: list iterator

  • It is obtained through the ListIterator() method of the list collection, so it is a unique iterator of the list collection
  • A list iterator that allows the programmer to traverse the list in either direction, modify the list during the iteration, and get the current position of the iterator in the list

Common methods in ListIterator

  • E next(): returns the next element in the iteration
  • boolean hasNext(): returns true if the iteration has more elements
  • E previous(): returns the previous element in the list
  • boolean hasPrevious(): returns true if this list iterator has more elements when traversing the list in the opposite direction
  • Void add (E): inserts the specified element into the list
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

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

        //Add element
        list.add("hello");
        list.add("world");
        list.add("java");

//        //Obtained through the listIterator() method of the list collection
//        ListIterator<String> lit = list.listIterator();
//        while (lit.hasNext()){
//            String s = lit.next();
//            System.out.println(s);
//        }
//        System.out.println("------------");
//
//        while (lit.hasPrevious()){
//            String s = lit.previous();
//            System.out.println(s);
//        }
//        System.out.println("------------");

        //Get list iterator
        ListIterator<String> lit = list.listIterator();
        while (lit.hasNext()){
            String s = lit.next();
            if (s.equals("world")){
                lit.add("javaee");
            }
        }
        System.out.println(list);//[hello, world, javaee, java]
    }
}

2.6. Enhanced for loop

Enhanced for: simplifies traversal of arrays and collection s

  • Classes that implement the Iterable interface allow their objects to be the target of enhanced for statements
  • It appeared after JDK5, and its internal principle is an Iterator iterator

Enhanced format for

  • format

For (element data type variable name: array or collection Collection){

/ / just use the variable here, which is the element

}

import java.util.ArrayList;
import java.util.List;

public class ForDemo {

    public static void main(String[] args) {
        int[] arr = {1,2,3};
        for (int i:arr){
            System.out.println(i);
        }
        System.out.println("-----");

        String[] strArray = {"hello","world","java"};
        for (String s:strArray){
            System.out.println(s);
        }
        System.out.println("-----");

        //Create collection object
        List<String> list = new ArrayList<String>();

        //Add element
        list.add("hello");
        list.add("my");
        list.add("dp");

        for (String s:list){
            System.out.println(s);
        }
        System.out.println("-----");

        //The internal principle is an Iterator iterator
//        for (String s:list){
//            if (s.equals("my")){
//                list.add("java");// An error ConcurrentModificationException is reported, which proves to be an Iterator iterator
//            }
//        }
    }
}

2.7 characteristics of List aggregation subclass

List collection common subclasses: ArrayList, LinkedList

  • ArrayList: the underlying data structure is an array, with fast query and slow addition and deletion
  • LinkedList: the underlying data structure is a linked list, with slow query and fast addition and deletion
import java.util.ArrayList;
import java.util.LinkedList;

public class ListDemo2 {
    public static void main(String[] args) {
        //Create collection object
        ArrayList<String> array = new ArrayList<>();

        array.add("hello");
        array.add("world");
        array.add("java");

        //ergodic
        for (String s:array){
            System.out.println(s);
        }
        System.out.println("------------");

        LinkedList<String> linkedList = new LinkedList<>();

        linkedList.add("hello");
        linkedList.add("world");
        linkedList.add("java");

        for (String s:linkedList){
            System.out.println(s);
        }

    }
}

3,Set

3.1 overview and characteristics of Set

Set set features:

  • A collection that does not contain duplicate elements
  • Without an indexed method, you can't use a normal for loop to traverse
/*
    Set Collection features:
* ==Collection without duplicate element = =
* ==There is no indexed method = =, so you can't use ordinary for loop traversal

       HashSet: The iterative order of the set is not guaranteed
 */


import java.util.HashSet;
import java.util.Set;

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

        //Add element
        set.add("hello");
        set.add("world");
        set.add("java");
        //A collection that does not contain duplicate elements
        set.add("world");

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

}

3.2. Hash value

It is a numeric value of type int calculated by JDK according to the address or 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 by the same object, and the returned hash value is the same
  • By default, the hash values of different objects are different. Rewriting the hashCode() method can make the hash values of different objects the same

3.3 overview and characteristics of HashSet set

HashSet set features

  • The underlying data structure is a hash table
  • The iterative order of the set is not guaranteed, that is, the order of stored and extracted elements is not guaranteed
  • Without an indexed method, you can't use a normal for loop to traverse
  • Because it is a Set set, all sets do not contain duplicate elements
import java.util.HashSet;
/*
   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 extracted elements is not guaranteed
* Without an indexed method, you can't use a normal for loop to traverse
* Because it is a Set set, all sets do not contain duplicate elements
 */
public class HashSet01 {
    public static void main(String[] args) {
        //Create collection object
        HashSet<String> hs = new HashSet<>();

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

        hs.add("world");

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

3.4. LinkedHashSet set overview and features

LinkedHashSet collection overview

  • The Set interface implemented by hash table and linked list has predictable iteration 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
import java.util.LinkedHashSet;
/*
    LinkedHashSet Collection overview:
* The Set interface implemented by hash table and linked list has = = predictable iteration 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==
 */
public class LinkedHashDemo {
    public static void main(String[] args) {
        //Create collection object
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();

        //Add element
        linkedHashSet.add("hello");
        linkedHashSet.add("world");
        linkedHashSet.add("java");

        linkedHashSet.add("world");

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

    }
}

3.5 overview and characteristics of TreeSet collection

TreeSet set features

  • 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

/*
    TreeSet Set characteristics
* 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 comparator): Sorts 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
 */

import java.util.TreeSet;

public class TreeSetDemo<I extends Number> {
    public static void main(String[] args) {
        TreeSet<Integer> ts = new TreeSet<Integer>();

        ts.add(10);
        ts.add(50);
        ts.add(30);
        ts.add(40);
        ts.add(80);

        ts.add(30);//A collection that does not contain duplicate elements

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

3.6 use of natural sorting Comparable

  • Store the student object and traverse it, create a TreeSet collection, and use a parameterless constructor
  • 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 (To) method
  • When rewriting a method, be sure to note that the collation must be written according to the required primary and secondary conditions

be careful:

When creating a TreeSet collection using a parameterless constructor, the Student class should implement the Comparable interface

import java.util.TreeSet;

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

        //Create student object
        Student s1 = new Student("Dapeng", 25);
        Student s2 = new Student("b Xiao Ming", 20);
        Student s3 = new Student("Xiao Hong", 35);
        Student s4 = new Student("Xiao Hui", 15);

        Student s5 = new Student("a Xiao Gang", 20);
        Student s6 = new Student("a Xiao Gang", 20);//Repeat no output

        //Add students to collection
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);

        ts.add(s5);
        ts.add(s6);

        //Traversal set
        for (Student s : ts){
            System.out.println(s.getName()+": "+s.getAge());
        }

    }
}


import java.util.Objects;

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

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

    public Student() {
    }

    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;
    }


    //Rewriting the hashCode() method can make the hash values of different objects the same
//    @Override
//    public int hashCode() {
//        return 0;
//    }


    @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);
    }
    @Override
    public int compareTo(Student s){
//        return 0;// Duplicate elements, do not add
//        return 1;// Ascending order
//        return -1;// Descending order
        //Sorted by age
        int num = this.age-s.age;//this refers to s2 and s refers to s1 in ascending order
//        int num = s.age - this.age;// Descending order
        //When the age is the same, sort alphabetically by name
        int num2 = num==0?this.name.compareTo(s.name):num;
        return num2;
    }
}


3.7 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
import java.util.Comparator;
import java.util.TreeSet;

public class TreeSet case {
    public static void main(String[] args) {
        //Create collection object
        TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //this.age - s.age
                //s1,s2
                int num = s1.getAge() - s2.getAge();//Ascending order
//                int num = s2.getAge() - s1.getAge();// Descending order
                int num2 = num == 0? s1.getName().compareTo(s2.getName()):num;
                return num2;
            }
        });

        //Create student object
        Student s1 = new Student("Dapeng", 25);
        Student s2 = new Student("b Xiao Ming", 20);
        Student s3 = new Student("Xiao Hong", 35);
        Student s4 = new Student("Xiao Hui", 15);

        Student s5 = new Student("a Xiao Gang", 20);
        Student s6 = new Student("a Xiao Gang", 20);//Repeat no output

        //Add students to collection
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);

        ts.add(s5);
        ts.add(s6);

        //Traversal set
        for (Student s : ts){
            System.out.println(s.getName()+": "+s.getAge());
        }
    }
}


public class Student{
    private String name;
    private int age;

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

    public Student() {
    }

    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;
    }

}

3.8. Case: ranking of achievements

/*
    Requirements:
        Use TreeSet set to store multiple student information (name, Chinese score, mathematics score), and traverse the set
        Requirements: appear from high to bottom according to the total score
    Idea:
        1.Define student classes
        2.Create a TreeSet collection object and sort by comparator sorting
        3.Create student object
        4.Add student object to collection
        5.Traversal set
 */


import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetDemo {

    public static void main(String[] args) {
        //Create a TreeSet collection object and sort by comparator sorting
        TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s2.getSum() - s1.getSum();
                int num2 = num ==0?s1.getChinese()-s2.getChinese():num;
                int num3 = num2 ==0?s1.getName().compareTo(s2.getName()):num2;
                return num3;
            }
        });

        //Create student object
        Student s1 = new Student("Wang Jie", 90, 98);
        Student s2 = new Student("Lin Junjie", 98, 96);
        Student s3 = new Student("Jay Chou", 96, 80);
        Student s4 = new Student("Kun yuan", 100, 100);
        Student s5 = new Student("Xufeng", 95, 95);

        Student s6 = new Student("Jin mi", 96, 94);
        Student s7 = new Student("Runyu", 96, 94);

        //Add student object to collection
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);

        ts.add(s6);
        ts.add(s7);

        //Traversal set
        for (Student s:ts){
            System.out.println(s.getName() +",Language achievement:"+s.getChinese()+",Math scores:"+s.getMath()+",Total score:"+s.getSum());
        }

    }

}


public class Student {
  private String name;
  private int chinese;
  private int math;

    public Student() {
    }

    public Student(String name, int chinese, int math) {
        this.name = name;
        this.chinese = chinese;
        this.math = math;
    }

    public String getName() {
        return name;
    }

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

    public int getChinese() {
        return chinese;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }

    public int getSum(){
        return this.chinese+this.math;
    }
}


4. Generics

4.1 generic overview

Essence: parameterized type ---- parameterize the type from the original specific type, and then pass in the specific type when using / calling

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

Benefits of generics:

  • It is more rigorous to advance the problems during operation to the compilation period
  • Casts are avoided

4.2. Generic classes

Define format:

  • Format: modifier class class name < type > {}
  • Example: public class Generic {}
    • Here, T can be written as any identifier. Common parameters such as T, E, K and v are often used to represent generics
public class GenericDemo {
    public static void main(String[] args) {
        Student s = new Student();
        s.setName("Lin Qingxia");
        System.out.println(s.getName());

        Teacher t = new Teacher();
        t.setAge(30);
        System.out.println(t.getAge());

        Generic<String> g1 = new Generic<String>();
        g1.setT("Lin Qingxia");
        System.out.println(g1.getT());

        Generic<Integer> g2 = new Generic<>();
        g2.setT(30);
        System.out.println(g2.getT());
        
        Generic<Boolean> g3 = new Generic<Boolean>();
        g3.setT(true);
        System.out.println(g3.getT());

    }
}


public class Student {
    private String name;

    public String getName() {
        return name;
    }

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


public class Teacher {
    private Integer age;

    public Integer getAge() {
        return age;
    }

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


public class Generic<T> {
    private T t;

    public T getT() {
        return t;
    }

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

4.3 generic methods

Define format:

  • Format: modifier < type > return type method name (type variable name) {}
  • Example: public void show (T) {}
public class GenericDemo {
    public static void main(String[] args) {
//        Generic g = new Generic();
//        g.show("Lin Qingxia");
//        g.show(30);
//        g.show(true);
//Generic class improvement
//        Generic<String> g1 = new Generic<String>();
//        g1.show("Zhang Jie");
//
//        Generic<Integer> g2 = new Generic<Integer>();
//        g2.show(25);
//
//        Generic<Boolean> g3 = new Generic<Boolean>();
//        g3.show(true);

Generic method improvement
        Generic g = new Generic();
        g.show("Zhang Jie");
        g.show(30);
        g.show(false);


    }

}


//public class Generic {

//    public void show(String s){
//        System.out.println(s);
//    }
//
//    public  void show(Integer i){
//        System.out.println(i);
//    }
//
//    public void show(Boolean b){
//        System.out.println(b);
//    }
//}


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

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

4.4 generic interface

Define format:

  • Format: modifier interface interface name < type > {}
  • Example: public interface Generic {}
public class GenericDemo {
    public static void main(String[] args) {
        Generic<String> g1 = new GenericImpl<String>();
        g1.show("Lin Qingxia");

        Generic<Integer> g2 = new GenericImpl<Integer>();
        g2.show(30);
    }
}


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


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

4.5 type wildcard

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

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

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 type >
  • List<? Super Number >: the type it represents is Number or its parent type
import java.util.ArrayList;
import java.util.List;

public class GenericDemo {
    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 > the type it represents is < font color ='Red '> number or its subtype < / font >
//        List<?  extends Number> list4 = new ArrayList<Object>();// report errors
        List<? extends Number> list5 = new ArrayList<Number>();
        List<? extends Number> list6 = new ArrayList<Integer>();
        System.out.println("---------");

        //Type wildcard lower limit: <? Super type > the type it represents is < font color ='Red '> number or its parent type < / font >
        List<? super Number> list7 = new ArrayList<Object>();
        List<? super Number> list8 = new ArrayList<Number>();
//        List<?  super Number> list9 = new ArrayList<Integer>();// report errors
        
    }

}

4.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, including variable parameters, the variable parameters should be placed last
public class ArgsDemo01 {
    public static void main(String[] args) {
        System.out.println(sum(10,20));
        System.out.println(sum(10,20,30));
        System.out.println(sum(10,20,30,40));
        System.out.println(sum(10,20,30,40,50));

    }

//    public static int sum(int b,int... a){
//        return 0;
//    }
    
    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;
//    }
}

4.7 use of variable parameters

There is a static method in the Arrays tool class:

  • public staticList asList(T... a): returns a fixed size list supported by the specified array
  • The returned collection cannot be added, deleted or modified, but can be modified

There is a static method in the List interface:

  • public static List of (E... elements): returns an immutable list containing any number of elements
  • The returned collection cannot be added, deleted or modified
  • The public static List of (E... elements) can be used only if the version is java 9 [list (Java se 9 & JDK 9) (Oracle. Com)]

There is a static method in the Set interface:

  • public static Set of(E... elements): returns an immutable set containing any number of elements
  • When giving elements, you cannot give duplicate elements
  • The returned collection cannot be added, deleted or modified. There is no modification method
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class ArgsDemo02 {
    public static void main(String[] args) {
        //1. Public static < T > List < T > aslist (t... A): returns a fixed size list supported by the specified array
        List<String> list = Arrays.asList("hello","world","java");

//        list.add("javaee");//UnsupportedOperationException
//        list.remove("world");//UnsupportedOperationException
        list.set(1,"javaee");
        System.out.println(list); //[hello, javaee, java]

        //2. Public static < E > List < E > of (E... Elements): returns an immutable list containing any number of elements
        //of doesn't work. The version can only be used if java 9
//        List<String> list = List.of("hello", "world", "java", "world");
//        list.add("javaee");//UnsupportedOperationException
//        list.remove("world");//UnsupportedOperationException
//        list.set(1,"javaee");
//
//        System.out.println(list);

        //3. Public static < E > set < E > of (E... Elements): returns an immutable set containing any number of elements
//        Set<String> set = Set.of("hello", "world", "java");
//        set.add("javaee");//UnsupportedOperationException
//        set.remove("world");//UnsupportedOperationException
//
//        System.out.println(set);

    }
}

5,Map

5.1 overview and use of Map set

Map collection overview

  • Interface map < K, V > k: type of key V: type of value

  • Objects that map keys to values; Cannot contain duplicate keys; Each key can be mapped to a maximum of one value

  • Example: student number and name

    it01 Lin Qingxia

    it02 Maggie Cheung

    it03 Wang Zuxian

Create an object for the Map collection

  • Polymorphic way
  • The specific implementation class is HashMap
import java.util.HashMap;
import java.util.Map;

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

        //V put(K key, V value) associates the specified value with the specified key in the map
        map.put("it01","Lin Qingxia");
        map.put("it02","Zhang Manyu");
        map.put("it03","Wang Zuxian");//{it02 = Zhang Manyu, it01 = Lin Qingxia, it03 = Wang Zuxian}

        //Output collection object
        System.out.println(map);


    }
}

5.2 basic functions of Map set

import java.util.HashMap;
import java.util.Map;

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

        //Add element
        map.put("zhang wuji","Zhao Min");
        map.put("Guo Jing","Huang Rong");
        map.put("Guo Yang","little dragon maiden");

        System.out.println(map);//{Yang Guo = Xiao Longnv, Guo Jing = Huang Rong, Zhang Wuji = Zhao Min}

        //Delete key value pair elements according to key
//        System.out.println(map.remove("Guo Jing")// Huang Rong
//        System.out.println(map.remove("Guo Xiang")// null
//
//        System.out.println(map);// {Yang Guo = Xiao Longnv, Zhang Wuji = Zhao Min}

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

//        System.out.println(map);//{}

        //Determines whether the collection contains the specified key
        System.out.println(map.containsKey("Guo Jing"));
        System.out.println(map.containsValue("little dragon maiden"));

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

        System.out.println(map.size());


    }
}

5.3. Acquisition function of Map set

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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

        //Add element
        map.put("zhang wuji","Zhao Min");
        map.put("Guo Jing","Huang Rong");
        map.put("Guo Yang","little dragon maiden");

        //Get value according to key
        System.out.println(map.get("zhang wuji"));//Zhao Min
        System.out.println(map.get("Zhang Sanfeng"));//null

        //Set < k > keyset(): get the set of all keys
        Set<String> keyset = map.keySet();
        for (String key:keyset){
            System.out.println(key);
        }

        //Collection < V > values(): get the collection of all values
        Collection<String> values = map.values();
        for (String value:values){
            System.out.println(value);
        }


    }
}

5.4. Traversal of Map set (mode 1)

The elements we just stored appear in pairs, so we regard the Map as a collection of husband and wife pairs

Traversal idea

  • Put all the husbands together
  • Traverse the collection of husbands and get each husband
  • According to the husband, find the corresponding wife

Convert to actions in the Map collection:

  • Get the collection of all keys and implement it with the keySet () method
  • Traverse the set of keys, get each key, and implement it with enhanced for
  • Find the value according to the key and use the get (Object key) method
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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

        //Add element
        map.put("zhang wuji","Zhao Min");
        map.put("Guo Jing","Huang Rong");
        map.put("Guo Yang","little dragon maiden");

        //Gets a collection of all keys. Using keySet() method
        Set<String> keyset = map.keySet();
        //Traverse the collection of keys and get each key. Implementation with enhanced for
        for (String key:keyset){
            //Find the value according to the key. It is implemented by get(Object key) method
            String value = map.get(key);
            System.out.println(key+","+value);
        }

    }

}

5.5. Traversal of Map set (mode 2)

The elements we just stored appear in pairs, so we regard the Map as a collection of each couple

Traversal idea:

  • Get a collection of all marriage certificates
  • Traverse the collection of marriage certificates to get each marriage certificate
  • Obtain husband and wife according to marriage certificate

Convert to operations in the Map collection

  • Gets a collection of all key value pair objects

    Set<Map.Entry<K,V> >entrySet()

  • Traverse the collection of key value pair objects to get each key value pair object

    Implement with enhanced for to get each map Entry

  • Get keys and values for objects based on key values

    • Get the key with getKey()
    • Get value with getValue
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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

        //Add element
        map.put("zhang wuji","Zhao Min");
        map.put("Guo Jing","Huang Rong");
        map.put("Guo Yang","little dragon maiden");

        //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){
            //Get keys and values for objects based on key values
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(key+","+value);
        }

    }
}

5.6. Case: the HashMap set stores student objects and traverses them

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashMapDemo {
    public static void main(String[] args) {
        //Create a HashMap collection object
        HashMap<String, Student> hm = new HashMap<String, Student>();

        //Create student object
        Student s1 = new Student("Lin Qingxia",30);
        Student s2 = new Student("Zhang Manyu",35);
        Student s3 = new Student("Wang Zuxian",33);

        //Add students to collection
        hm.put("IT01",s1);
        hm.put("IT02",s2);
        hm.put("IT03",s3);

        //Method 1: key value finding
        Set<String> keySet = hm.keySet();
        for (String key:keySet){
            Student value = hm.get(key);
            System.out.println(key+","+value.getName()+","+value.getAge());
        }

        //Method 2: find keys and values for objects
        Set<Map.Entry<String, Student>> entrySet = hm.entrySet();
        for (Map.Entry<String, Student> me:entrySet){
            String key = me.getKey();
            Student value = me.getValue();
            System.out.println(key+","+value.getName()+","+value.getAge());

        }

    }
}

public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    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;
    }
}


import java.util.HashMap;
import java.util.Set;

public class HashMapDemo02 {
    public static void main(String[] args) {
        //Create a HashMap collection object
        HashMap<Student, String> hm = new HashMap<>();

        //Create student object
        Student s1 = new Student("Lin Qingxia",30);
        Student s2 = new Student("Zhang Manyu",35);
        Student s3 = new Student("Wang Zuxian",33);
        Student s4 = new Student("Wang Zuxian",33);

        //Add students to collection
        hm.put(s1,"Xi'an");
        hm.put(s2,"Wuhan");
        hm.put(s3,"Zhengzhou");
        hm.put(s4,"Beijing");//Wang Zuxian's location has changed from Zhengzhou to Beijing. You need to rewrite hashCode(), equals(), or there will be two Wang Zuxian

        //Traversal set
        Set<Student> keySet = hm.keySet();
        for (Student key:keySet){
            String value = hm.get(key);
            System.out.println(key.getName()+","+key.getAge()+","+value);
        }


    }

}


import java.util.Objects;

public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    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;
    }

    @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);
    }
}

5.7. The ArrayList set stores HashMap elements and traverses them

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class ArrayListIncludeHashMapDemo {
    public static void main(String[] args) {
        //Create an ArrayList collection
        ArrayList<HashMap<String, String>> array = new ArrayList<HashMap<String, String>>();

        //Create a HashMap collection and add key value pair elements
        HashMap<String, String> hm1 = new HashMap<>();
        hm1.put("Sun CE","Big Joe");
        hm1.put("Zhou Yu","Little Joe");
        //Add the HashMap as an element to the ArrayList collection
        array.add(hm1);

        HashMap<String, String> hm2 = new HashMap<>();
        hm2.put("Guo Jing","Huang Rong");
        hm2.put("Guo Yang","little dragon maiden");
        //Add the HashMap as an element to the ArrayList collection
        array.add(hm2);

        HashMap<String, String> hm3 = new HashMap<>();
        hm3.put("linghu chong","Ren yingying");
        hm3.put("Lin Pingzhi","Yue Lingshan");
        //Add the HashMap as an element to the ArrayList collection
        array.add(hm3);

        //Traversing the ArrayList collection
        for (HashMap<String, String> hm:array){
            Set<String> keySet = hm.keySet();
            for (String key:keySet){
                String value = hm.get(key);
                System.out.println(key+","+value);
            }
        }


    }
}

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class HashMapIncludeArrayListDemo {
    public static void main(String[] args) {
        //Create a HashMap collection
        HashMap<String, ArrayList<String>> hm = new HashMap<>();

        //Create an ArrayList collection and add elements
        ArrayList<String> sgyy = new ArrayList<>();
        sgyy.add("Zhuge Liang");
        sgyy.add("Zhao Yun");
        //Add ArrayList as an element to the HashMap collection
        hm.put("Romance of the Three Kingdoms",sgyy);

        ArrayList<String> xyj = new ArrayList<>();
        xyj.add("Tang Monk");
        xyj.add("Sun WuKong");
        //Add ArrayList as an element to the HashMap collection
        hm.put("Journey to the West",xyj);

        ArrayList<String> shz = new ArrayList<>();
        shz.add("Wu Song");
        shz.add("lu zhishen");
        //Add ArrayList as an element to the HashMap collection
        hm.put("Water Margin",shz);

        //Traverse the HashMap collection
        Set<String> keySet = hm.keySet();
        for (String key:keySet){
            System.out.println(key);
            ArrayList<String> value = hm.get(key);
            for (String s:value){
                System.out.println("    "+s);
            }
        }

    }
}

6,Collections

6.1. Overview and use of Collections

Overview of the Collections class

  • Is a tool class for collection operations

Common methods of Collections class

  • public static<T extends Comparable<? Super T > > void sort (list): sort the specified list in ascending order
  • Public static void reverse (list <? > list): reverses the order of elements in the specified list
  • Public static void shuffle (list <? > list): randomly arrange the specified list using the tacit random source
import java.util.ArrayList;
import java.util.Collections;

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

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

        //public static<T extends Comparable<?  Super T > > void sort (list < T > list): sort the specified list in ascending order
//        Collections.sort(list);
//        System.out.println(list);//[10, 20, 30, 40, 50]

        //Public static void reverse (list <? > list): reverses the order of elements in the specified list
//        Collections.reverse(list);
//        System.out.println(list);//[40, 20, 50, 10, 30]

        //Public static void shuffle (list <? > list): randomly arrange the specified list using the tacit random source
        Collections.shuffle(list);
        System.out.println(list);//[20, 30, 10, 50, 40]


    }
}

6.2. Case: ArrayList stores and sorts student objects

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class CollectionsDemo02 {
    public static void main(String[] args) {
        ArrayList<Student> array = new ArrayList<Student>();

        //Create student object
        Student s1 = new Student("Lin Qingxia",30);
        Student s2 = new Student("Zhang Manyu",35);
        Student s3 = new Student("Wang Zuxian",33);

        //Add students to collection
        array.add(s1);
        array.add(s2);
        array.add(s3);

        //Sorting the ArrayList collection using Collections
        //sort (List<T> list,Comparator<? super T> c)
        Collections.sort(array, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //Sort by age from small to large. When the age is the same, sort by name alphabetically
                int num = s1.getAge() - s2.getAge();
                int num2 = num ==0?s1.getName().compareTo(s2.getName()):num;
                return num2;
            }
        });

        //Traversal set
        for (Student s:array){
            System.out.println(s.getName()+","+s.getAge());
        }

    }
}

.util.ArrayList;
import java.util.Collections;

public class CollectionsDemo {
public static void main(String[] args) {
//Create collection object
ArrayList list = new ArrayList();

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

    //public static<T extends Comparable<?  Super T > > void sort (list < T > list): sort the specified list in ascending order

// Collections.sort(list);
// System.out.println(list);//[10, 20, 30, 40, 50]

    //Public static void reverse (list <? > list): reverses the order of elements in the specified list

// Collections.reverse(list);
// System.out.println(list);//[40, 20, 50, 10, 30]

    //Public static void shuffle (list <? > list): randomly arrange the specified list using the tacit random source
    Collections.shuffle(list);
    System.out.println(list);//[20, 30, 10, 50, 40]


}

}



### 6.2. Case: ArrayList stores and sorts student objects

[External chain picture transfer...(img-faxCj86k-1630291556995)]



```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class CollectionsDemo02 {
    public static void main(String[] args) {
        ArrayList<Student> array = new ArrayList<Student>();

        //Create student object
        Student s1 = new Student("Lin Qingxia",30);
        Student s2 = new Student("Zhang Manyu",35);
        Student s3 = new Student("Wang Zuxian",33);

        //Add students to collection
        array.add(s1);
        array.add(s2);
        array.add(s3);

        //Sorting the ArrayList collection using Collections
        //sort (List<T> list,Comparator<? super T> c)
        Collections.sort(array, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //Sort by age from small to large. When the age is the same, sort by name alphabetically
                int num = s1.getAge() - s2.getAge();
                int num2 = num ==0?s1.getName().compareTo(s2.getName()):num;
                return num2;
            }
        });

        //Traversal set
        for (Student s:array){
            System.out.println(s.getName()+","+s.getAge());
        }

    }
}

Topics: Java