javaSE basic collection (collection Collection)

Posted by exhaler on Tue, 04 Jan 2022 02:23:34 +0100

Course notes Day14

  • Collection collection
  • List collection
  • Set set

Chapter 1 Collection

Section 01 basic theory

Origin of collection

What are the characteristics of arrays?

1. Any data type (basic data type or reference data type) can be stored
2. The length of the array is fixed and cannot be changed

Among the above features, we know that the length of the array is fixed and cannot meet the changing needs. Sometimes, the length needs to change constantly. In this case, what should we do?

You need to use collection classes to complete.

Features of the collection:

1. You can store reference data types. (cannot store basic data type)
2. The length is variable

A collection is a container, such as our water cup. According to the data stored in the container, the size, shape and data structure are different. Divide the collection into different types.

Collection architecture

Section 02 common methods

Method introduction

Method APIMethod description
public boolean add(E)Adds the specified object to the collection
public boolean remove(E)Deletes the specified object from the collection
public void clear()Empty all elements in the collection
public boolean contains(E)Determines whether the collection contains the specified element
public boolean isEmpty()Judge whether the current collection is empty
public int size()Returns the number of elements in the collection
public Object[] toArray()The elements in the collection are stored in the array

quick get start

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

//Objective: to learn a quick start to the Collection
public class Test01 {

    public static void main(String[] args) {

        //Create object: left parent and right child, polymorphic writing
        Collection<String> c = new ArrayList<>();

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

        //Show results
        System.out.println(c); //[hello, world, java]
    }
}

//Summary:
//1. Create the object format in a polymorphic way
//2. Add data using the add() method
//3. The toString() method has been overridden in the ArrayList set

Section 03 collection traversal

Method 1: toArray to array

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

//Objective: to learn the toArray method of Collection
public class Test03 {

    public static void main(String[] args) {
        //create object
        Collection<String> c = new ArrayList<>();
        c.add("hello");
        c.add("world");
        c.add("java");
        //Object[] toArray()
        //Direct call method
        Object[] objects = c.toArray();
        for (int i = 0; i < objects.length; i++) {
            System.out.println(objects[i]);
        }
        System.out.println("-----------");
        //<T> T[]  toArray(T[] a)
        //    T[]  toArray(T[] a)
        //    String[]  toArray(String[] a)
        String[] strings = c.toArray(new String[c.size()]);
        for (int i = 0; i < strings.length; i++) {
            System.out.println(strings[i]);
        }
    }
}
//Summary:
//The toArray() method converts a collection into an array.
//If there is a generic type, you will get an array of specific types. If there is no generic type, it will be an Object array

Mode 2: iterator

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

//Objective: to learn the basic use of Iterator
public class Test04 {

    public static void main(String[] args) {

        //create object
        Collection<String> c = new ArrayList<>();
        c.add("hello");
        c.add("world");
        c.add("java");

        //Shortcut key for writing code: C.It itIt
        //Get the iterator's object iterator < string > through set c
        Iterator<String> iter = c.iterator();
        //Loop through the data ITER Hasnext() to see if the next data exists
        while (iter.hasNext()) {
            //Get the current data ITER next();
            String next = iter.next();
            //Show results
            System.out.println(next);
        }
    }
}
//Summary: about using iterators
//1. Get the iterator object c.iterator();
//2. Cycle judge ITER Does hasnext() have a next element
//3. Get the current element ITER next()

How iterators work

Precautions for iterators: Concurrent modification exception

Method 3: enhance the for loop

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

//Objective: learn to enhance the for loop to traverse the set
@SuppressWarnings("all")
public class Test06 {

    public static void main(String[] args) {

        //create object
        Collection<String> c = new ArrayList<>();
        c.add("hello");
        c.add("world");
        c.add("java");
        //Use the enhanced for loop to traverse the collection. Shortcut key: c.for enter
        for (String s : c) {
            System.out.println(s);
        }
    }
}

Note: in the enhanced for loop, you can't add or delete a collection, otherwise there will be concurrent modification exceptions. ConcurrentModificationException

To put it simply, the enhanced for loop is a simplified version for iterators. Our professional term is "grammar sugar"

Chapter 2 List set

Section 01 basic theory

Characteristics of List set

(1) Order: the order of storage is consistent with the order of retrieval
(2) Duplicate: duplicate elements can be stored
(3) Indexed: have indexed methods

Method introduction

Method APIMethod description
void add(int,E)In the list, specify the index position and insert elements
E remove(int)In the list, delete the element at the specified index position
E set(int,E)In the list, modify the element at the specified index position
E get(int)List, get the element at the specified index position

List collection traversal

Traversal of collection

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

//Traversal of the List collection
//1. To array
//2. Iterator
//3. Enhance for
//4. Ordinary for
@SuppressWarnings("all")
public class Test02 {

    public static void main(String[] args) {
        //Create object (polymorphic writing: left parent right child)
        List<String> mList = new ArrayList<>();
        //Add data
        mList.add("Delireba");
        mList.add("Gulinaza");
        mList.add("Marzaha");
        System.out.println("1. To array:");
        String[] array = mList.toArray(new String[mList.size()]);
        for (int i = 0; i < array.length; i++) {
            System.out.println(array[i]);
        }
        System.out.println("2. iterator :");
        Iterator<String> iter = mList.iterator();
        while (iter.hasNext()) {
            String next = iter.next();
            System.out.println(next);
        }
        System.out.println("3. enhance for");
        for (String s : mList) {
            System.out.println(s);
        }
        System.out.println("4. ordinary for");
        for (int i = 0; i < mList.size(); i++) {
            System.out.println(mList.get(i));
        }
    }
}

Section 02 ArrayList set

Classical problem

stay ArrayList What should I pay attention to when deleting a collection?

code

//Target: delete of collection
public class Test04 {

    public static void main(String[] args) {
        //Create the object of the collection
        ArrayList<String>  array = new ArrayList<>();
        //Add data
        array.add("Delireba");
        array.add("Zhang Sanfeng");
        array.add("Guo Jing");
        array.add("Huang Rong");
        array.add("zhang wuji");
        array.add("linghu chong");
        array.add("Oriental mushroom mother");
        array.add("Track Point ");
        //Note: delete the person whose name is two words.
        for (int i = 0; i < array.size(); i++) {
            //Get everyone's name
            String s = array.get(i);
            //Determine the length and size of elements in the collection
            if (s.length() == 2){
                array.remove(s);
                i--;  //After deletion, add an i-- operation
            }
        }
        //Printout results
        for (String s : array) {
            System.out.println(s);
        }
    }
}
//Note: in the process of deletion, you need to add i--
//The main reason is that in the process of collection deletion, the length is changing and the data moves forward.

Section 03 LinkedList set

The underlying structure is linked list (fast addition and deletion, slow query)

Method APIMethod description
public void addFirst(E)Adds the specified element to the beginning of this list
public void addLast(E)Adds 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()Remove and return the first element of this list
public E removeLast()Remove and return the last element of this list
public E pop()From this list, an element pops up in the stack, which is equivalent to removeFirst
public void push(E)From this list, push the element into the first element on the stack, which is equivalent to addFirst

Chapter 3 Set

Section 01 basic theory

Characteristics of Set

(1)Disorder: the order of storage and removal may be inconsistent
(2)No duplicate: duplicate elements cannot be stored
(3)No index: there is no indexed method

quick get start

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

//Objective: learn a quick start to the Set collection
public class Test01 {

    public static void main(String[] args) {

        //Create object (polymorphic writing: left parent right child)
        Set<String> set = new HashSet<>();
        set.add("hello");
        set.add("hello");
        set.add("world");
        set.add("java");
        set.add("java");
        set.add("java");
        set.add("hello");
        System.out.println("set = " + set); //set = [world, java, hello]
        //How to traverse a collection?
        //iterator 
        Iterator<String> iter = set.iterator();
        while (iter.hasNext()) {
            String next = iter.next();
            System.out.println(next);
        }
        //Enhanced for
        for (String s : set) {
            System.out.println(s);
        }
    }
}

Section 02 HashSet set

demand

use HashSet Collection stores custom objects and iterates through them.

Case code

Coach class

//Coach class
public class Coach {
    private String name;
    private int age;

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

        Coach coach = (Coach) o;

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

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

    public Coach() {
    }

    public Coach(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 "Coach{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Test class

import java.util.HashSet;

//Objective: learn to store custom objects in the HashSet collection
public class Test02 {

    public static void main(String[] args) {

        //Create a collection object and add data
        HashSet<Coach> set = new HashSet<>();
        Coach c1 = new Coach("Liu Guoliang",50);
        Coach c2 = new Coach("Yao Ming",40);
        Coach c3 = new Coach("Du Feng",50);
        Coach c4 = new Coach("Liu Guoliang",50);

        //Add data
        set.add(c1);
        set.add(c2);
        set.add(c3);
        set.add(c4);

        //Show results
        for (Coach c : set) {
            System.out.println(c);
        }
    }
}

HashSet set de duplication principle

If you want to be right HashSet For collection de duplication, two methods need to be rewritten: [both are indispensable]
	1. hashCode() Method: returns the name of the object hash Value. An integer calculated from an attribute
	2. equals() Method: compare whether the properties of two objects are the same.

emphasize hash The concept of value.
	A. The same object can be called multiple times hashCode() method, hash The values are the same.
	B. Different objects, calling hashCode() method, hash The values may be the same. (string) "conversation" and  "Heavily")

For the process description of HashSet set de duplication:

1. Compare first hash Whether the values are the same.
	A. If hash If the values are different, the system recognizes two objects as different. (there is no need to compare later)
	B. If hash If the values are the same, the system also needs to compare the attribute values according to equals() Methods to compare.
2. stay hash When the values are the same, compare equals Value.
	A. If equals The result of the comparison is true It means the same. Cannot store
	B. If equals The result of the comparison is false It means different and can be stored

design sketch

Section 03 TreeSet set

quick get start

//Objective: to learn the TreeSet set
public class Test04 {

    public static void main(String[] args) {

        //create object
        TreeSet<Integer> ts = new TreeSet<>();
        ts.add(19);
        ts.add(11);
        ts.add(17);
        ts.add(13);
        ts.add(13);
        ts.add(13);
        ts.add(13);
        ts.add(15);
        //Show results
        for (Integer num : ts) {
            System.out.println(num);
        }
    }
}
//Summary: what is the function of TreeSet set?
//1. Weight can be removed
//2. Can be sorted

The results of the operation are as follows:

11
13
15
17
19

Internal comparator

Student class

//Student class
public class Student implements Comparable<Student>{

    String name;
    int age;

    //Comparison rules:
    //Ascending order: this - o
    //Descending order: o - this
    @Override
    public int compareTo(Student o) {
        //Want to rank in ascending order of age
        int result = this.age - o.age;
        //When the age is the same, compare the names in descending order
        result = (result == 0)? o.name.compareTo(this.name):result;
        return result;
    }

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

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

Test class

import java.util.TreeSet;

public class Test05 {

    public static void main(String[] args) {

        TreeSet<Student> ts = new TreeSet<>();
        Student stu1 = new Student("zhanhang",18);
        Student stu2 = new Student("zhanhang",19);
        Student stu3 = new Student("wanghan",18);
        ts.add(stu1);
        ts.add(stu2);
        ts.add(stu3);
        ts.add(stu3);
        //Show results
        for (Student stu : ts) {
            System.out.println(stu);
        }
    }
}
//Student{name='zhanhang', age=18}
//Student{name='wanghan', age=18}
//Student{name='zhanhang', age=19}

External comparator

Teacher class

//Teacher class
public class Teacher {

    String name;
    int age;

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

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

Test class

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

//Objective: learn the external comparator
public class Test06 {

    public static void main(String[] args) {

        //An external comparator can be used to complete the comparison operation
        TreeSet<Teacher> ts = new TreeSet<>(new Comparator<Teacher>() {
            //Ascending order: o1 - o2
            //Descending order: o2 - o1
            @Override
            public int compare(Teacher o1, Teacher o2) {
                int result = o1.age - o2.age;
                result = (result==0)?o2.name.compareTo(o1.name):result;
                return result;
            }
        });
        //Create a teacher's object
        Teacher one = new Teacher("hualaoshi",33);
        Teacher two = new Teacher("huashishi",50);
        Teacher three = new Teacher("huahua",50);
        Teacher four = new Teacher("huahua",50);
        Teacher five = new Teacher("zhangsan",40);
        //Add data to the collection
        ts.add(one);
        ts.add(two);
        ts.add(three);
        ts.add(four);
        ts.add(five);
        //Show results
        for (Teacher t : ts) {
            System.out.println(t);
        }
    }
}

Today's summary:

Collection framework

Collection is a container provided in JAVA to store multiple data.

I've learned about arrays before. Arrays are also a kind of data container, but arrays are very inconvenient to use. The difference is:

  • Array features: fixed type and fixed length

  • Collection features: the type is not fixed, the length is not fixed, and any data is stored at will

    JAVA provides a lot of different collections. Select the appropriate collection in different scenarios. These many collections are called collection framework.

The collection framework is roughly divided into two categories: single column collection and Java util. Collection and double column collection Java util. Map and collection framework are all located in Java Util package

Iterator interface

In the development process, it is often necessary to traverse all elements in the Collection. JDK provides an interface java util. Iterator. It is different from the Collection and Map interfaces. The Collection and Map interfaces are mainly used to store elements, while the iterator is mainly used to iteratively access (i.e. traverse) the elements in the Collection. Therefore, the iterator object is also called an iterator.

To traverse the Collection, you need to obtain the Collection iterator to complete the iterative operation. The following describes the method of obtaining the iterator:

  • public Iterator iterator(): get the iterator corresponding to the collection and use it to traverse the elements in the collection.

  • Iteration: in short, you use a loop to traverse all elements from scratch. The iterative method is to judge whether there are elements in the set before taking elements. If there are, take out this element, continue to judge, and take out if there are any. Always take out all the elements in the collection. This extraction method is called iteration in technical terms.

The common methods of Iterator interface are as follows:

  • public E next(): returns the next element of the iteration.
  • public boolean hasNext(): returns true if there are still elements that can be iterated.

Code demonstration

public static void main(String[] args) {
    //        Prepare sets and elements
    List<String> list = new ArrayList<>();
    list.add("Guan Yu");
    list.add("Fei Zhang");
    list.add("Liu Bei");
    list.add("Zhao Yun");
    list.add("Zhuge Liang");

    //        Gets the iterator corresponding to the collection
    Iterator<String> iterator = list.iterator();
    //        Judge whether there is a next element each time. If yes, return true; otherwise, return false
    while (iterator.hasNext()){
        String hero = iterator.next();
        System.out.println(hero);
    }

}

2.2 implementation principle

We have completed the whole process of Iterator traversing the collection in the previous case. When traversing the collection, first obtain the Iterator object by calling the iterator() method of the t collection, and then use the hashNext() method to judge whether there is the next element in the collection. If so, call the next() method to take out the element. Otherwise, it indicates that the end of the collection has been reached, and stop traversing the element.

Iterator uses the index pointer to complete the traversal process. Before calling the next method of the iterator, the iterator's index is located before the first element and does not point to any element. After calling the next method of the iterator for the first time, the iterator's index will move back one bit, point to the first element and return the element. When calling the next method again, the iterator's index will point to the second element and return the element, And so on, until the hasNext method returns false, indicating that the end of the collection is reached and the traversal of the element is terminated.

Iterator is a fast failure, which means that after obtaining the iterator, the data structure of the collection cannot be modified until the traversal is completed. Otherwise, a ConcurrentModificationException will occur. If the element needs to be deleted during the iteration, it can only be implemented through the void remove() method of iterator, not the remove method of the collection.

Code demonstration

public static void main(String[] args) {
    //        Prepare sets and elements
    List<String> list = new ArrayList<>();
    list.add("Guan Yu");
    list.add("Fei Zhang");
    list.add("Liu Bei");
    list.add("Zhao Yun");
    list.add("Zhuge Liang");

    //        Gets the iterator corresponding to the collection
    Iterator<String> iterator = list.iterator();
    //      If the collection structure is modified after obtaining the iterator, an exception will occur
    //        list.add("Huang Zhong");

    //        Judge whether there is a next element each time. If yes, return true; otherwise, return false
    while (iterator.hasNext()){
        String hero = iterator.next();
        System.out.println(hero);
        //            If the structure of the collection is modified during traversal, an exception will occur
        //            list.remove(hero);
    }

}

tips: enhancing the bottom layer of the for loop is implemented through iterators, so when using this method, it also fails quickly.

Topics: Java intellij-idea