Summary of knowledge points [nanny level]

Posted by JayBlake on Sun, 16 Jan 2022 07:08:11 +0100

1, Collection

Features of collection class: it provides a storage type with variable storage space, and the stored data capacity can be changed at any time

Collection collection overview

  • Is the top-level interface of a single column 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

  • Create in a polymorphic way
  • The specific implementation class is ArrayList
import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo01 {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();

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

        //Output collection object
        System.out.println(c);	//[hello, world, java]
    }
}

1.1 common methods of collection

Method nameexplain
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

1.2 traversal of collection

Iterator: iterator, a special traversal mode of a collection

  • Iterator < E > iterator(): returns the iterator in this collection, which is obtained through the iterator() method of the collection
  • The iterator is obtained through the iterator() method of the set, so we say that it depends on the set

Common methods in Iterator

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

public class TeacherTest {
    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();

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

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

        Iterator<String> iterator = c.iterator();

        //Traversal set
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

1.3 case: the Collection stores student objects and traverses them

Requirements: create a collection of student objects, store 3 student objects, and the utility program traverses the collection on the console

Idea:

  • Define student classes
  • Collection object creation collection
  • Create student object
  • Add students to collection
  • Traversal collection (iterator mode)

Student.java

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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

CollectionDemo.java

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

public class CollectionDemo {
    public static void main(String[] args) {
        Collection<Student> c = new ArrayList<>();
        Student s1 = new Student("Zhang San",18);
        Student s2 = new Student("Li Si",19);
        Student s3 = new Student("Wang Wu",20);

        c.add(s1);
        c.add(s2);
        c.add(s3);
        Iterator<Student> it = c.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

2, List

List collection overview

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

Characteristics of List set

  • Ordered: the stored and retrieved elements are in the same order
  • Repeatable: stored elements can be repeated
import java.util.ArrayList;
import java.util.List;

public class CollectionDemo {
    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();

        list.add("hello");
        list.add("hello");
        list.add("world");
        System.out.println(list);
    }
}

2.1 common methods of list set

Method nameexplain
void add(int index, E element)Inserts the specified element at the specified location in this collection
E remove(int index)Delete the element exported from the specified index and return the deleted element
E set(int index, E element)Modify the element exported from the specified index and return the modified element
E get(int index)Returns the element at the specified index

2.2 the list set stores student objects and traverses them

Requirements: create a collection for storing student objects, store 3 student objects, and use the program to traverse the collection on the console

Idea:

  • Define student classes
  • Create a List collection object
  • Create student object
  • Add student object to collection
  • Traversing a collection (iterator or for loop mode)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ListDemo {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        Student s1 = new Student("Zhang San",19);
        Student s2 = new Student("Li Si",20);
        Student s3 = new Student("Wang Wu",21);

        list.add(s1);
        list.add(s2);
        list.add(s3);

        //iterator 
        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.3 concurrent modification exception

Concurrent modification exception

  • ConcurrentModificationException

Cause

  • During the iterator traversal, the length of the elements in the set is modified through the set object, resulting in the inconsistency between the judgment tone modification value and the actual modification value in the elements obtained by the iterator

Solution

  • Use the for loop to traverse, and then use the collection object to do the corresponding operation

2.4 ListIterator list iterator

ListIterator: list iterator

  • It is obtained through the listIterator() method of the List set, so it is a unique iterator of the List set
  • It is used to allow the programmer to traverse the list iterator in any direction, modify the list during iteration, and obtain the current position of the iterator in the list

Common methods of ListIterator

Method nameexplain
E next()Returns the next element in the iterator
boolean hasNext()Returns true if the iterator 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 e)Insert the specified element into the list

2.5 enhanced for loop

Enhanced for: simplifies traversal of arrays and Collection collections

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

Enhanced for format

  • format

    • for(Element data type variable name:Array or Collection aggregate){
          //The variable is used here. The variable is the element
      }
      
  • example

    • int[] arr = {1,2,3,4,5};
      for(int i:arr){
          System.out.println(i);
      }
      

2.6 data structure

Data structure is a way for computers to store and organize data. A collection of data elements that have one or more specific relationships with each other.

In general, carefully selected data structures can lead to higher operation or storage efficiency

2.6.1 stack of common data structures

2.6.2 queues of common data structures

2.6.3 arrays of common data structures

2.6.4 linked list of common data structures

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

2.8 unique functions of LinkedList set

Method nameexplain
public void addFirst(E e)Inserts the specified element at the beginning of the list
public void addLast(E e)Appends the specified element to the end of this list
public E getFirst()Returns the first element of this list
public E getLast()Returns the last element of this list
public E removeFirst()Removes and returns the first element from this list
public E removeLast()Removes and returns the last element from this list

3, Set

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

Set set exercise

  • Store string and traverse
public class SetDemo {
    public static void main(String[] args) {
        Set<String> s = new HashSet<>();
        s.add("hello");
        s.add("world");
        s.add("java");
        for (String i : s) {
            System.out.println(i);
        }
    }
}

3.1 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 that can get the hash value of the Object

  • public int hashCode(): returns the hash code 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 make the hash values of different objects the same

3.2 HashSet set overview and features

Hash set features

  • The underlying data structure is a hash table
  • There is no guarantee that the iterative order of the set is the same, that is, the order of storing and fetching 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 said that it does not contain duplicate elements

3.2.1 source code analysis of HashSet set to ensure element uniqueness

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


3.2.2 case: the HashSet set stores student objects and traverses them

Requirements: create a collection for storing student objects, store multiple student objects, and use the program to traverse the collection on the console

Requirement: if the member variable values of the student object are the same, we think it is the same object

Idea:

  • Define a student class
  • Create a HashSet collection object
  • Create student object
  • Add students to collection
  • Traversal collection (enhanced for)
  • Override two methods in the student class
    • hashCode() and equals()

Student.java

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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", 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;

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

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

HashSetDemo.java

import java.util.*;

public class HashSetDemo {
    public static void main(String[] args) {
        HashSet<Student> hs = new HashSet<>();

        Student s1 = new Student("Zhang San", 18);
        Student s2 = new Student("Li Si", 19);
        Student s3 = new Student("Wang Wu", 20);

        Student s4 = new Student("Zhang San", 18);

        hs.add(s1);
        hs.add(s2);
        hs.add(s3);
        hs.add(s4);

        for (Student i :
                hs) {
            System.out.println(i.getName() + "," + i.getAge());
        }
    }
}

3.3 LinkedHashSet set overview and features

LinkedHashSet set features

  • 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 retrieval of elements are consistent
  • There is a hash table to ensure the uniqueness of elements, that is, there are no duplicate elements

LinkedHashSet set exercise

  • Store string and traverse
import java.util.*;

public class CollectionDemo {
    public static void main(String[] args) {
        LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
        linkedHashSet.add("hello");
        linkedHashSet.add("world");
        linkedHashSet.add("java");
        linkedHashSet.add("hello");

        for (String i :
                linkedHashSet) {
            System.out.println(i);
        }
    }
}

Output results:

hello
world
java

3.4 overview and characteristics of TreeSet set

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

TreeSet set exercise

  • Store integers and traverse
public class TreeSetDemo {
    public static void main(String[] args) {
        //Create collection object
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(18);
        ts.add(50);
        ts.add(30);
        ts.add(20);

        ts.add(30);

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

Output results:

18
20
30
50

3.4.1 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 letters 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(T o) method
  • When rewriting a method, be sure to note that the collation must be written according to the required primary and secondary conditions

Student.java

package com.wangkai;

//Implement Comparable interface
public class Student implements Comparable<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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    //Override compareTo method
    @Override
    public int compareTo(Student s) {
        int num = this.age - s.age;
        int num2 = num == 0 ? this.name.compareTo(s.name) : num;
        return num2;
    }
}

TreeSetDeom2.java

import java.util.*;

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

        //Create student object
        Student s1 = new Student("Zhang San", 30);
        Student s2 = new Student("Li Si", 28);
        Student s3 = new Student("Xiao Ming", 41);
        Student s4 = new Student("Wang Wu", 20);

        Student s5 = new Student("Cao Cao", 20);
        Student s6 = new Student("Wang Wu", 20);

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

        for (Student i :
                ts) {
            System.out.println(i.getName()+","+i.getAge());
        }

    }
}

Output results:

Cao Cao,20
 Wang Wu,20
 Li Si,28
 Zhang San,30
 Xiao Ming,41

3.4.2 use of 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

Conclusion:

  • The TreeSet collection is used to store custom objects, and the substitute meal construction method uses a comparator to sort elements
  • Comparator sorting is to let the collection construction method accept the implementation object of comparator and override the compare(T o) method
  • When rewriting a method, be sure to note that the collation is written according to the required primary and secondary conditions

Student.java

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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

}

TreeSetDeom3.java

import java.util.*;

public class TreeSetDeom3 {
    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) {

                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("Zhang San", 30);
        Student s2 = new Student("Li Si", 28);
        Student s3 = new Student("Xiao Ming", 41);
        Student s4 = new Student("Wang Wu", 20);

        Student s5 = new Student("Cao Cao", 20);
        Student s6 = new Student("Wang Wu", 20);

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

        for (Student i :
                ts) {
            System.out.println(i.getName()+","+i.getAge());
        }
    }
}

Output results:

Cao Cao,20
 Wang Wu,20
 Li Si,28
 Zhang San,30
 Xiao Ming,41

3.4.3 cases: 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 low according to the total score

Idea:

  • Define student classes
  • Create a TreeSet collection object and sort it through a comparator
  • Create student object
  • Add student object to collection
  • Traversal set

Student.java

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.getChinese()+this.getMath();
    }

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

TreeSetDemo.java

import java.util.*;

public class TreeSetDemo {
    public static void main(String[] args) {
        TreeSet<Student> st = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                int num = s2.getSum()-s1.getSum();
                return num;
            }
        });

        Student s1 = new Student("Zhang San", 80, 70);
        Student s2 = new Student("Li Si", 40, 68);
        Student s3 = new Student("Wang Wu", 30, 99);
        Student s4 = new Student("Xiao Ming", 64, 78);
        Student s5 = new Student("Zhao Liu", 76, 56);

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

        for (Student i :
                st) {
            System.out.println("full name:"+i.getName()+"\t Language achievement:"+i.getChinese()+"\t Math scores:"+i.getMath()+"\t Total score:"+i.getSum());
        }

    }
}

3.5 case: random number without repetition

Requirements: write a program to obtain 10 random numbers between 1 and 20. It is required that the random numbers cannot be repeated and output on the console

Idea:

  • Create Set collection object
  • Create random number
  • Judge whether the length of the set is less than 10
    • Yes: generate a random number and add it to the collection
    • Go back to 3 and continue
  • Traversal set
public class SetDemo {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        Random random = new Random();

        while (set.size()<10) {
            set.add(random.nextInt(20)+1);
        }
        for (Integer i :
                set) {
            System.out.println(i);
        }
    }
}

4, Generics

Genericity: a feature introduced in JDK5, it provides a compile time type safety detection mechanism, which allows illegal types to be detected at compile time

Its essence is parameterized type, that is, the data type operated on is specified as a parameter

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 original specific type of the type, and then pass in the specific parameter type when using / calling

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 types here are treated as formal parameters
  • 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:

  • The problem of running 17 is advanced to the compilation period
  • Migration to type conversion is avoided

4.1 generic classes

Definition format of generic class:

  • Format: modifier class class name < type > {}
  • Example: public class generic < T > {}
    • Here, T can be arbitrarily identified by Ctrip. Common parameters such as T, E, K and V are often used to represent generics

4.2 generic methods

Definition format of generic method:

  • Format: modifier < type > return value type method name (type variable name) {}
  • Example: public < T > void show (T) {}

4.3 generic interfaces

Definition format of generic interface:

  • Format: modifier interface interface name < type > {}
  • Example: public interface generic < T > {}

4.4 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. 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 <? > The upper limit of type wildcard can be used when the parent class of any generic List only wants 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: <? Super type >
  • List<? Super Number >: indicates that the type is Number or its parent type
public class GenericDemo {
    public static void main(String[] args) {
        List<?> list1 = new ArrayList<Object>();
        List<?> list2 = new ArrayList<Number>();
        List<?> list3 = new ArrayList<Integer>();

//        List<?  extends Number> list4 = new ArrayList<Object>();     report errors
        List<? extends Number> list5 = new ArrayList<Number>();
        List<? extends Number> list6 = new ArrayList<Integer>();

        List<? super Number> list7 = new ArrayList<Object>();
        List<? super Number> list8 = new ArrayList<Number>();
//        List<?  super Number> list9 = new ArrayList<Integer>();      report errors
    }
}

4.5 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 a here is actually an array
  • If a method has many parameters, including variable parameters, the variable parameters should be placed last

4.6 use of variable parameters

There is a static method in the Array tool class:

  • Public static < T > List < T > aslist (t... a): returns a list of fixed sizes supported by a specified array
  • The returned collection cannot be added or deleted, but can be modified
  • List< String > list = Arrays.asList("hello","world","java");

There is a static method in the List interface (JDK9):

  • 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
  • List< String > list = List.of("hello","world","java");

There is a static method in the Set interface (JDK9):

  • Public static < E > set < E > of (E... elements): returns an immutable set containing any number of elements
  • You cannot give duplicate elements when you give them
  • The returned collection cannot be added or deleted, and there is no modification method
  • Set< String > set = Set.of("hello","world","java");

5, Map

Map collection overview:

  • Interface map < K, V > k: type of key; 5: Value type
  • Objects that map keys to values; Cannot contain duplicate keys; Each key can be mapped to a maximum of one value

Create a Map collection object

  • Polymorphic way
  • The specific implementation class is HashMap
public class CollectionDemo {
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();

        map.put("a001","Zhang San");
        map.put("a002","Li Si");
        map.put("a003","Wang Wu");
        map.put("a004","Xiao Ming");

        System.out.println(map);
    }
}

Basic functions of Map collection

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 each set

Get function of Map collection

Method nameexplain
V get(Object key)Get the value according to the key
Set< K > ketSet()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

Traversal of Map collection (mode 1)

The elements we just stored appear in pairs, so let's treat Map as a collection of husband and wife pairs

Traversal idea

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

Operations in the Map set:

  • Gets a collection of all keys. It is implemented using the keySet() method
  • Traverse the collection of keys and get each key. Using enhanced for loop
  • Find the value according to the key and use the get(Object key) method
import java.util.*;

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

        map.put("a001","Zhang San");
        map.put("a002","Li Si");
        map.put("a003","Wang Wu");

        Set<String> keySet = map.keySet();

        for (String i :
                keySet) {
            String s = map.get(i);
            System.out.println(i+","+s);
        }
    }
}

Traversal of Map set (mode 2)

The elements we just stored appear in pairs, so let's treat Map as a collection of husband and wife pairs

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 actions in the Map collection:

  • Gets a collection of all key value pair objects
    • Set<Map. Entry < K, V > > entryset(): get the set of all key value pair objects
  • Traverse the collection of key value pair objects to get each key value pair object
    • Use the enhanced for loop to get each map Entry
  • Get keys and values for objects based on key values
    • Get the key with getKey()
    • Get the value with getValue()
import java.util.*;

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

        map.put("a001","Zhang San");
        map.put("a002","Li Si");
        map.put("a003","Wang Wu");

        Set<Map.Entry<String, String>> entries = map.entrySet();

        for (Map.Entry<String, String> me :
                entries) {
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(key+","+value);
        }
    }
}

5.1 case: the HashMap set stores student objects and traverses them

Requirements: create a HashMap set. The key is the Student number (String) and the value is the Student object (Student). Store three key value pair elements and traverse them

Idea:

  • Define student objects
  • Create a HashMap collection object
  • Create student object
  • Add students to collection
  • Traversal set
    • Method 1: key value finding
    • Method 2: find key value for object

Student.java

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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

HashMapDemo.java

import java.util.*;

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

        Student s1 = new Student("Zhang San",29);
        Student s2 = new Student("Li Si",31);
        Student s3 = new Student("Wang Wu",25);

        map.put("a001",s1);
        map.put("a002",s2);
        map.put("a003",s3);

        //Mode 1
        Set<String> keySet = map.keySet();
        for (String i :
                keySet) {
            Student s = map.get(i);
            System.out.println("Student No.:"+i+"\t full name:"+s.getName()+"\t Age:"+s.getAge());
        }

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

        //Mode 2
        Set<Map.Entry<String, Student>> entrySet = map.entrySet();
        for (Map.Entry<String, Student> i :
                entrySet) {
            String key = i.getKey();
            Student value = i.getValue();
            System.out.println("Student No.:"+key+"\t full name:"+value.getName()+"\t Age:"+value.getAge());
        }

    }
}

5.2 case: the HashMap set stores student objects and traverses (changes)

Requirement: create a HashMap set, with the key being Student and the value being String. Store multiple key value pair elements and traverse them

It is required to ensure the uniqueness of the key: if the member variable values of the student object are the same, we think it is the same object

Idea:

  • Define student classes
  • Create a HashMap collection object
  • Create student object
  • Add student object to collection
  • Traversal set
  • Override two methods in the student class
    • hashCode()
    • equals()

Student.java

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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", 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;

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

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

HashMapDemo.java

import java.util.*;

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

        Student s1 = new Student("Zhang San",29);
        Student s2 = new Student("Li Si",31);
        Student s3 = new Student("Wang Wu",25);
        Student s4 = new Student("Wang Wu",25);

        map.put(s1,"Beijing");
        map.put(s2,"Shanghai");
        map.put(s3,"Guangzhou");
        map.put(s4,"Guangzhou");

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

5.3 case: the ArayList set stores HashMap elements and traverses them

Requirements: create an ArrayList collection, store three elements, each element is a HsahMap, the key and value of each HashMap are String, and traverse

Idea:

  • Create an ArrayList collection
  • Create a HashMap collection and add key value pair elements
  • Add the HashMap as an element to the ArrayList collection
  • Traversing the ArrayList collection
import java.util.*;

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

        //Create a HashMap collection
        HashMap<String, String> hm1 = new HashMap<>();
        hm1.put("Sun CE", "Big Joe");
        hm1.put("Zhou Yu", "Little Joe");
        array.add(hm1);

        HashMap<String, String> hm2 = new HashMap<>();
        hm2.put("Guo Jing", "Huang Rong");
        hm2.put("Guo Yang", "little dragon maiden");
        array.add(hm2);

        HashMap<String, String> hm3 = new HashMap<>();
        hm3.put("linghu chong", "Ren yingying");
        hm3.put("Lin Pingzhi", "Yue Lingshan");
        array.add(hm3);

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

5.4 case: the HashMap set stores the ArrayList element and traverses it

Requirements: create a HashMap set, store three key value pair elements, the key of each key value pair element is String, the value is ArrayList, and the element of each ArrayList is String, and traverse

Idea:

  • Create a HashMap collection
  • Create an ArrayList collection and add elements
  • Add ArrayList as an element to the HashMap collection
  • Traverse the HashMap collection
import java.util.*;

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

        ArrayList<String> sanguo = new ArrayList<>();
        sanguo.add("Zhuge Liang");
        sanguo.add("Zhao Yun");
        hm.put("Romance of the Three Kingdoms", sanguo);

        ArrayList<String> xiyou = new ArrayList<>();
        xiyou.add("Tang Monk");
        xiyou.add("Sun WuKong");
        hm.put("Journey to the West", xiyou);

        ArrayList<String> shuihu = new ArrayList<>();
        shuihu.add("Wu Song");
        shuihu.add("lu zhishen");
        hm.put("Water Margin", shuihu);

        Set<String> keySet = hm.keySet();
        for (String key :
                keySet) {
            ArrayList<String> array = hm.get(key);
            for (String i :
                    array) {
                System.out.println(key+","+i);
            }
        }
    }
}

5.5 case: count the number of occurrences of each string in the string

Requirement: enter a string on the keyboard and count the number of occurrences of each string in the string.

Example: keyboard input "aababcacdabcde" console output: "a(5)b(4)c(3)d(2)e(1)"

analysis:

  • We can divide the results into several parts: a(5),b(4),c(3),d(2),e(1)
  • Each part can be regarded as: the number of times corresponding to characters and strings
  • Such data can be stored through the HashMap collection. The key is the character and the value is the number of times the character appears
  • Note: the key is a Character, and the type should be Character; The value is the number of occurrences of the Character. The type should be Integer

Idea:

  • Enter a string on the keyboard
  • Create a HashMap collection with the key Character and the value Integer
  • Traverse the string to get each character
  • Take each character as a key to find the corresponding value in the HashMap collection and see its return value
    • If the return value is null: it indicates that the character does not exist in the HashMap collection, the character is stored as a key and 1 as a value
    • If the return value is not null: it indicates that the character exists in the HashMap collection, add 1 to the value, and then re store the value corresponding to the character
  • Traverse the HashMap set, get the keys and values, and splice them as required
  • Output results
import java.util.*;

public class HashMapDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a string:");
        String s = sc.next();

        HashMap<Character, Integer> hashMap = new HashMap<>();

        //Traverse the string to get each character
        for (int i = 0;i<s.length();i++){
            char key = s.charAt(i);
            Integer value = hashMap.get(key);

            if (value == null){
                hashMap.put(key,1);
            }else{
                value++;
                hashMap.put(key,value);
            }
        }

        StringBuilder builder = new StringBuilder();
        Set<Character> keySet = hashMap.keySet();
        for (Character key:
              keySet) {
            Integer value = hashMap.get(key);
            builder.append(key).append("(").append(value).append(")");
        }
        System.out.println(builder.toString());
    }
}

6, 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 < T > 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 default random source
import java.util.*;

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

        list.add(40);
        list.add(30);
        list.add(60);
        list.add(10);
        list.add(20);

        System.out.println(list);

        //Ascending sort
        Collections.sort(list);
        System.out.println(list);

        //Invert element
        Collections.reverse(list);
        System.out.println(list);

        //Random permutation
        Collections.shuffle(list);
        System.out.println(list);
    }
}

6.1 case: ArrayList stores and sorts student objects

Requirements: ArrayList stores objects and uses Collections to sort ArrayList

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

Idea:

  • Define student classes
  • Create an ArrayList collection object
  • Create student object
  • Add students to collection
  • Sorting the ArrayList collection using Collections
  • Traversal set

Student.java

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 String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

CollectionsDemo.java

import java.util.*;

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

        Student s1 = new Student("Zhang San", 23);
        Student s2 = new Student("Li Si", 26);
        Student s3 = new Student("Wang Wu", 21);
        Student s4 = new Student("Wang Liu", 21);

        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                //in years
                int num = s1.getAge() - s2.getAge();
                int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
                return num2;
            }
        });

        for (Student s :
                list) {
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

6.2 case: simulated landlords

Requirements: shuffle, deal and watch cards in the national politics of landlords through procedures

Idea:

  • Create a card box, that is, a collection object, which is implemented with the ArrayList collection
  • Put cards in the card box
  • Shuffle, that is, break up the cards, and implement it with the shuffle() method of Collections
  • Deal, that is, traverse the set and deal cards to three players
  • Look at cards, that is, three players traverse their cards respectively
import java.util.*;

public class PukeDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();

        //Define Decor array
        String[] colors = {"♦", "♣", "♥", "♠"};
        //Define an array of points
        String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};

        for (String color :
                colors) {
            for (String number :
                    numbers) {
                list.add(color + number);
            }
        }
        list.add("Xiao Wang");
        list.add("king");

        //shuffle the cards
        Collections.shuffle(list);

        //Licensing
        ArrayList<String> zhangsan = new ArrayList<>();
        ArrayList<String> lisi = new ArrayList<>();
        ArrayList<String> wangwu = new ArrayList<>();
        ArrayList<String> dipai = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            String puke = list.get(i);
            if (i >= list.size() - 3) {
                dipai.add(puke);
            } else if (i % 3 == 0) {
                zhangsan.add(puke);
            } else if (i % 3 == 1) {
                lisi.add(puke);
            } else if (i % 3 == 2) {
                wangwu.add(puke);
            }
        }

        //Look at the cards
        lookPoker("Zhang San",zhangsan);
        lookPoker("Li Si",lisi);
        lookPoker("Wang Wu",wangwu);
        lookPoker("a hand",dipai);
    }

    //How to look at cards
    public static void lookPoker(String name, ArrayList<String> list) {
        System.out.print(name+"The cards are:");
        for (String i :
                list) {
            System.out.print(i+" ");
        }
        System.out.println();
    }
}

6.3 case: simulated landlords upgrade

Requirements: shuffle, deal and watch cards in the process of fighting landlords through procedures

Requirement: sort the cards

Idea:

  • To create a HashMap, the key is the number and the value is the card
  • Create an ArrayList and store the number
  • Create Decor array and point array
  • Start from 0, store the number in the HashMap and store the corresponding card. At the same time, the number is stored in the ArrayList
  • Shuffle (shuffle the number) with the shuffle() method of Collections
  • Licensing (the licensing is also numbered. In order to ensure that the numbers are sorted, create a TreeSet set to receive)
  • Define the card watching method (traverse the TreeSet set, get the number, and find the corresponding card in the HashMap set)
  • Call card reading method
import java.util.*;

public class PukeDemo2 {
    public static void main(String[] args) {
        //Number key yes, value card
        HashMap<Integer, String> map = new HashMap<>();

        //Storage number
        ArrayList<Integer> array = new ArrayList<>();

        //Create decor and point array
        String[] colors = {"♦", "♣", "♥", "♠"};
        String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};

        int index = 0;
        for (String number :
                numbers) {
            for (String color :
                    colors) {
                map.put(index, color + number);
                array.add(index);
                index++;
            }
        }
        map.put(index, "Xiao Wang");
        array.add(index);
        index++;
        map.put(index, "king");
        array.add(index);

        //shuffle the cards
        Collections.shuffle(array);

        //Licensing
        TreeSet<Integer> zhangsan = new TreeSet<>();
        TreeSet<Integer> lisi = new TreeSet<>();
        TreeSet<Integer> wangwu = new TreeSet<>();
        TreeSet<Integer> dipai = new TreeSet<>();

        for (int i = 0; i < array.size(); i++) {
            int puke = array.get(i);
            if (i >= array.size() - 3) {
                dipai.add(puke);
            } else if (i % 3 == 0) {
                zhangsan.add(puke);
            } else if (i % 3 == 1) {
                lisi.add(puke);
            } else if (i % 3 == 2) {
                wangwu.add(puke);
            }
        }

        //Look at the cards
        lookPoker("Zhang San", zhangsan, map);
        lookPoker("Li Si", lisi, map);
        lookPoker("Wang Wu", wangwu, map);
        lookPoker("a hand", dipai, map);

    }

    //How to look at cards
    public static void lookPoker(String name, TreeSet<Integer> set, HashMap<Integer, String> map) {
        System.out.print(name + "The cards are:");
        for (Integer i :
                set) {
            System.out.print(map.get(i) + " ");
        }
        System.out.println();
    }
}

Topics: Java set HashMap arraylist