JavaSE advanced programming summary and training-summary of basic usage methods of collection 1 (List interface)

Summary of the basic usage of the collection

1. How to use ArrayList collection

Talk about the sorting of the object array

Here I will mainly use the sorting of records. I personally recommend using the comparator of Comparetor to do the sorting. The sample code is as follows:

import java.util.*;

/**
 * @author jiangzl
 */
public class MyArrayList {
    
    
    public static void main(String[] args){
    
    
        ArrayList myListOfTask = new ArrayList<Arraytask>();
        Scanner sc = new Scanner(System.in);
        for(int i = 0;i < 5;++i){
    
    
            String name = sc.next();
            int prio = sc.nextInt();
            myListOfTask.add(new Arraytask(name, prio));
        }
        sc.close();

        System.out.println("---------排序前---------");
        for(int i = 0;i < 5;++i){
    
    
            System.out.println(myListOfTask.get(i));
        }

        System.out.println("---------排序后---------");
        Collections.sort(myListOfTask, new Comparator<Arraytask>() {
    
    
            @Override
            public int compare(Arraytask tk1, Arraytask tk2) {
    
    
                if(tk1.getTaskPriority() != tk2.getTaskPriority()){
    
    
                    return tk2.getTaskPriority() - tk1.getTaskPriority();
                }
                else{
    
    
                    return tk1.getTaskName().compareTo(tk2.getTaskName());
                }
            }
        });

        for(int i = 0;i < 5;++i){
    
    
            System.out.println(myListOfTask.get(i));
        }
    }
}

/**
 * @author jiangzl
 */
class Arraytask{
    
    
    private String taskName;
    private int taskPriority;

    public Arraytask(String name, int prio){
    
    
        this.taskName = name;
        this.taskPriority = prio;
    }

    public String getTaskName(){
    
    
        return taskName;
    }

    public int getTaskPriority(){
    
    
        return taskPriority;
    }

    @Override
    public String toString(){
    
    
        return new String("任务名:" + taskName + " , 任务优先级:" + taskPriority);
    }
}
How to use the Comparetor comparator:

After writing a class, we need to sort the object array of this class. We can use the collection method:

Collection.sort(对象数组名(ArrayList 的对象名), new Comparetor<类名(泛型)>(){
    
    
			@Override
            public int compare(类名 obj1, 类名 obj2) {
    
    
                /……/
            }
})
Points to note:

① The return value of the compare function here is of type int. If it returns a positive number, it means that the previous object obj1 is greater than obj2, and a negative number is less than. Of course, 0 is equal.

② If you want to show a certain priority, here is the complete opposite of C++ is that obj2 (the latter) has a higher priority than obj1 (the former) by default. For example, in my sample code:

			@Override
            public int compare(Arraytask tk1, Arraytask tk2) {
    
    
                if(tk1.getTaskPriority() != tk2.getTaskPriority()){
    
    
                    return tk2.getTaskPriority() - tk1.getTaskPriority();
                }
                else{
    
    
                    return tk1.getTaskName().compareTo(tk2.getTaskName());
                }
            }

The meaning of the representative is:
(1) If the priority of the two tasks are not the same, let the one with the higher priority rank first. Because the default is that the latter is ranked first, so we return: When it meets the priority of our design, return a number greater than 0. So if it is the higher priority in the front, then the comparison mechanism of Comparetor is the latter in the front, so we design the latter value to be greater than the front, that is, it is called when the subtraction is greater than 1. ( Remarks : It may not be easy to understand here... It's because my writing is not good enough to write clearly)

(2) Generally speaking, it boils down to one point: if you want to sort in ascending order according to a certain reference value, make the front object obj1 larger than the latter, that is, obj1.val-obj2.val. For example, when we want the same priority, the names are sorted in ascending lexicographical order, so let the name of the first object minus the name of the second object, sort by greater than 0 (that is, ascending order)! Otherwise, let the back minus the front.

Briefly talk about the addition, deletion and modification of the object array (ArrayList)

(1) Traverse and read elements

This is still very simple. If it is just a "read" operation, the best method (the most efficient) is:

		int len = (ArrayList对象) arrayObj.size();
		for(int i = 0;i < len;++i){
    
    
            /……/
            类名 obj = arrayObj.get(i);
            /……/
        }

The efficiency under this "read" operation is the highest, which is higher than foreach (the result of experimental testing).

(2) Modify elements
		int len = (ArrayList对象) arrayObj.size();
		for(int i = 0;i < len;++i){
    
    
            /……/
            类名 update = new 类名(……) // 你的新改的对象
            类名 obj = arrayObj.set(i, update);
            /……/
        }
(3) Delete elements
		int len = (ArrayList对象) arrayObj.size();
		for(int i = 0;i < len;++i){
    
    
            /……/
            类名 remv = arrayObj.remove(i); // remv 就是你要删除的对象
            /……/
        }

Some explanations and summary of additions, deletions, and changes:

Use get(index) for reading, set(index, newObj) for modification, and remove(index) for deletion,
but the return values ​​of all three of them are objects! ! ! This needs attention!
And ArrayList is a vector-based data structure that can be accessed randomly! So from this bottom layer, it must be high reading and writing efficiency, and low efficiency in deleting and adding. So there is the following LinkedList collection

2. How to use the LinkedList collection

Talk about the Iterator interface and LinkedList traversal

Let's first look at a sample program:

import java.util.*;

/**
 * @author jiangzl
 */
public class MyLinkedList {
    
    
    public static void main(String[] args){
    
    
        LinkedList myList = new LinkedList<Student>();
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for(int i = 0;i < n;++i){
    
    
            String name = sc.next();
            int age = sc.nextInt();
            myList.add(new Student(name, age));
        }

        String delName = sc.next();
        Iterator<Student> it = myList.iterator();
        while(it.hasNext()){
    
    
            if(it.next().getName().equals(delName)){
    
    
                it.remove();
                break;
            }
        }

        while (it.hasNext()){
    
    
            System.out.println(it.next());
        }
    }
}

/**
 * @author jiangzl
 */
class Student{
    
    
    private String name;
    private int age;

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

    @Override
    public String toString(){
    
    
        return new String("姓名:" + name + " , 年龄:" + age);
    }

    public String getName(){
    
    
        return name;
    }
}

Here first talk about the traversal of LinkedList

We use the Iterator class to traverse, use the hasNext() method to determine whether there is a next value, and then use next() to get the object currently traversed! Then do what you need to do!

 		Iterator<类名> it = myList.iterator();
        while(it.hasNext()){
    
    
            类名 obj = it.next();
            /……/
        }

Let me say ListIterator interfaces, where the biggest difference is, ListIterator supports concurrent execution, but Iterator does not support! Take a look at a small example:

import java.util.*;
import java.util.ListIterator;

public class MyListIterator {
    
    
    public static void main(String[] args){
    
    
        List myList = new ArrayList();
        myList.add("stu1");
        myList.add("stu2");
        myList.add("stu3");
        myList.add("stu4");
        myList.add("stu5");
        ListIterator it = myList.listIterator();

        while(it.hasNext()){
    
    
            if("stu2".equals(it.next())){
    
    
                it.remove();
                it.add("hello");
                break;
            }
        }

        it = myList.listIterator();
        while(it.hasNext()){
    
    
            System.out.println(it.next());
        }
    }
}

Look at the output of the console:
Insert picture description here

Obviously we can see:
① The ListIterator interface can use the add() method to insert operations at the current iterator position.
② The ListIterator interface, for example, after a certain traversal is completed, if you need to traverse the object array again, you must re:

it = myList.listIterator();

③ The Iterator interface is read-only and is an attribute. If you want to modify it, you still have to use ListIterator to modify "stu2" to become "hello".

Then talk about adding, deleting, modifying and checking

This is actually very simple. If you use ListIterator, you can not only implement Iterator's it.remove(); to delete the object pointed to by the current iterator. You can also use the add(obj); method to insert the object obj after the position pointed to by the current iterator.
Just like this code in the example:

		while(it.hasNext()){
    
    
            if(it.next().getName().equals(delName)){
    
    
                it.remove();
                break;
            }
        }

        while (it.hasNext()){
    
    
            System.out.println(it.next());
        }

All operations rely on: it.next(); to get the object currently traversed, and then operate it!

Finally, summarize the methods extended after the List interface inherits from Collection:

Insert picture description here
I won’t talk about other methods, most of them are very simple.

Guess you like

Origin blog.csdn.net/qq_44274276/article/details/107774974