Comprehensive practical training of Java generics, collection framework, List interface, Iterator and Collections tool classes

 

1, Review of knowledge points

1. Java generics < >

Concept:

Generics are used to specify the data type you want to use. Angle brackets < > are used to indicate that the data type must be class.

For example, a Worker class is created and used as a generic type, < student >.

be careful:

  • The data type cannot be a native data type such as int or double.
  • It can be a class of native data type: Integer, String, etc.

2. Collection framework List interface

Concept:

Generic interface list < >. The generic classes that implement the generic interface include LinkedList < >, ArrayList < >.

Principle:

Interface callback technology is used, because most methods in LinkedList < > generic class are the implementation of methods in generic interface list < >. Therefore, by assigning the reference of the LinkedList < > object to the list < > interface variable, the interface can call the interface method implemented by the LinkedList < > class.

Code usage:

List<Student>  list=new LinkedList<Student>()

Common class methods:

  • Add object: list add(new Worker("","",""))
  • Delete object: list remove(index)
  • Statistics object: list size()
  • Get object: list get(index)

3. Collections utility class

Concept:

Collections tool class provides many class methods, which can sort, find, randomly sort, rotate and other class methods for collections.

Common class methods:

  • Sort in ascending order: collections sort(list)
  • Random sorting: collections shuffle(list)
  • Rotate sort: collections reverse(list)
  • Sort in descending order: first use sort() to sort in ascending order, and then use reverse() to rotate to achieve the purpose of descending order

When an object contains multiple attributes, how to sort one of them???

Example: the created worker object has three attributes: name, age and salary. So how to sort the wages in this object?

Thinking: the first thought must be to extract the wages of all workers and put them into a container separately (you can create a linked List of the List interface to store the extracted data), and then sort them using the Collections tool class.

Question: how can we extract the salary attribute from each worker object?

Scheme 1: List < integer > salarylist = list stream(). map(Worker ->Worker.getSalary()). collect (Collectors.toList());  

Now that all salaries have been stored in Salarylis, you only need to sort the Collections of Salarylist.

4. Iterator iterator traversal

Method to create Iterator iterator object:

You need to use the interface object list of the interface list to call the class method list Iterator () and assign it to the iter object created by iterator.

Traversal principle:

The Iterator object created by Iterator is equivalent to a pointer pointing to the first node of the created LinkedList linked list. After obtaining the first object node, the Iterator will automatically obtain the object data of the next node, so the Iterator can quickly traverse the collection.

Code usage:

Iterator<Worker>  iter=list.iterator()

Common class methods:

  • Empty object: ITER hasNext()
  • Get object: ITER next()

Traversal Code:

while( iter.hasNext() ){

Worker  worker = iter.next();

System.out.println(worker.name + worker.salary);

}

 

2, Actual combat cases

requirement:

1. Create a Worker class. The member variables include: name, age, salary and member method.

2. Create a list interface object and assign a value to the list interface using LinkedList.

3. Use class method list Add() adds worker information.

4. Use Iterator iterator to traverse and display worker information.

5. Use class method list Remove() deletes the worker Wahaha's information.

6. Use the class method in the Collections tool class to sort the workers' wages in descending order and output the sorted personal information.

Worker

public class Worker {

    public String Name;
    public int Age;
    public int Salary;

    public Worker(String Name, int Age, int Salary) {
        this.Name = Name;
        this.Age = Age;
        this.Salary = Salary;
    }

    public int getSalary() {
        return Salary;
    }

}

Test class WorkerTest

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class WorkerTest {

    public static void main(String[] args) {
        //1. The collection framework generic interface list creates the interface variable list, and the linked list LinkedList class implements the methods in the interface and assigns values to the interface variable list
        List<Worker> list = new LinkedList<Worker>();
        
        //2. Add objects using the class method add()
        list.add(new Worker("Zhang Yi", 33, 5500));
        list.add(new Worker("Zhang Er", 37, 6500));
        list.add(new Worker("Zhang San", 31, 4500));
        list.add(new Worker("Zhang Si", 39, 7000));
        list.add(new Worker("Zhang Wu", 36, 6300));
        
        //3. Create an Iterator iterator object, Iterator traversal, and create and assign values with the class method iterator() of the interface variable list
        Iterator<Worker> iter = list.iterator();
        while (iter.hasNext()) {
            Worker worker = iter.next();
            System.out.print(worker.Name + worker.Age + " " + worker.Salary + "    ");
        }
        System.out.println("");
        
        //4. Use the class method remove() to delete the object with the specified subscript
        list.remove(2);
        iter = list.iterator();
        while (iter.hasNext()) {
            Worker worker = iter.next();
            System.out.print(worker.Name + worker.Age + " " + worker.Salary + "    ");
        }
        System.out.println("");
        
        /*5,Use the Collections tool class to sort the elements in the linked list
        Requirement: sort wages in descending order
        Problem: (1) there are no descending class methods in the Collections tool class  
              (2),There are three attributes in the worker object. You need to extract the wages of all workers before sorting
        Scheme: (1) use class methods in two Collections tool classes: sort() ascending and reverse() rotating
              (2),Use list stream(). map(Worker -> Worker.getSalary()). Collect (collectors. Tolist()) extracts the salary in the object
                   Create a new list < integer > container to store all wages
                   map Function: convert the original data to the specified data
        */
        //The obtained salary data is stored in the new Salarylist interface variable
        List<Integer> Salarylist = list.stream().map(Worker -> Worker.getSalary()).collect(Collectors.toList());
        //Ascending sort
        Collections.sort(Salarylist);
        Iterator<Integer> Salaryiter = Salarylist.iterator();
        System.out.print("Ascending order of workers' wages:");
        while (Salaryiter.hasNext()) {
            int salary = Salaryiter.next();
            System.out.print(salary + "  ");
        }
        System.out.println("");
        //Rotating linked list
        Collections.reverse(Salarylist);
        Salaryiter = Salarylist.iterator();
        System.out.print("Descending order of workers' wages:");
        while (Salaryiter.hasNext()) {
            int salary = Salaryiter.next();
            System.out.print(salary + "  ");
        }
    }

}

 

 

 

 

Keywords: Java iterator LinkedList Collections

Added by anon_amos on Tue, 08 Feb 2022 04:57:05 +0200