The way of Java learning -- Collection class and List class

Work hard and see you at the top! come on.

1, Set system diagram


2, Collection class

1. Characteristics of Collection interface implementation class

public interface Collection<E> extends Iterable <E>
  1. The Collection implementation subclass can store multiple elements, and each element can be an Object.
  2. Some Collection implementation classes can store duplicate elements, while others cannot.
  3. Some Collection implementation classes are ordered (List), and some are not ordered (Set).
  4. The Collection interface does not directly implement subclasses, but is implemented through its sub interfaces Set and List.

2. Collection common methods

  1. Add: add a single element
  2. remove: deletes the specified element
  3. contains: find whether the element exists
  4. size: get the number of elements
  5. isEmpty: judge whether it is empty
  6. Clear: clear
  7. addAll: add multiple elements
  8. contains: find whether multiple elements exist
  9. removeAll: delete multiple elements

3. Collection interface - Iterator interface

The Collection interface traverses the elements in 1 --- > using the Iterator iterator

  1. The Iterator object is called an Iterator and is mainly used to traverse the elements in the Collection
  2. All Collection classes that implement the Collection interface have an iterator() method to return an object that implements the Iterator interface, that is, an Iterator can be returned.
  3. Structure of Iterator
  4. The Iterator is only used to traverse the collection, and the Iterator itself does not store objects.

Implementation principle of iterator

Iterator iterator = coll.iterator();//Get an iterator for a collection
while(iterator.hasNext()){//Move down to return the elements at the collection position after moving down
		System.out.println(iterator.next());
}

After calling iterator.next(); Method should be detected by using iterator.hasNext(). If not, when the next record is invalid, calling iterator.next() directly will throw NoSuchElementException.

Example of Iterator iterator usage:

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

public class Iterator_Learn {
    public static void main(String[] args) {
        Collection col=new ArrayList();//col is compiled as Collection and run as ArrayList
        //Upward transformation is used here

        col.add(new Book("Romance of the Three Kingdoms",10));
        col.add(new Book("Water Margin",20));
        col.add(new Book("Journey to the West",15));

        Iterator iterator=col.iterator();//Get an iterator
        while(iterator.hasNext()){
            Object next = iterator.next();
            System.out.println(next);
        }
			//Reset iterator position
        iterator=col.iterator();
    }
}

class Book{
    String name;
    double price;

    public Book(String name, double price) {
        this.name = name;
        this.price = price;
    }

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

Shortcut prompt:
Generate iterator: itit
Show shortcuts for all shortcuts: Ctrl+j

Method 2 of traversing elements through the Collection interface - > using the enhanced for loop, the bottom layer is still the iterator

for(Element type element name: Collection name or array name){
		Access element
}

//Example
for(Object book:col){
	System.out.println("book="+book);//book is created in the enhanced for loop to read the element.
}

3, List class

The List interface is a sub interface of the Collection interface

  1. The elements in the List collection class are orderly (that is, the addition order is consistent with the extraction order) and the elements can be repeated.
  2. Each element in the List collection has its corresponding sequential index, that is, it supports index.
  3. The elements in the List container correspond to an integer serial number, recording their position in the container. You can get the elements in the container as needed.
  4. The common implementation classes of List interface in JDK API are ArrayList, LinkedList and Vector.
import java.util.ArrayList;
import java.util.List;

public class List_ {
    public static void main(String[] args) {
        List list=new ArrayList();
        list.add("jack");
        list.add("tom");
        list.add("mary");
        list.add("hsp");
        System.out.println("list"+list);
        System.out.println(list.get(3));//2. Each element in the list set has its corresponding sequential index, that is, it supports index.
    }
}

List interface and common methods

Some methods are added to the List collection to manipulate the collection elements according to the index

  1. void add(int index,Object ele); Insert the ele element at the index position.
  2. boolean addAll(int index,Collection eles); Add all elements in eles from the index position.
  3. Object get(int index) gets the element at the specified index position.
  4. int indexOf(Object obj); Returns the position where obj first appears in the collection.
  5. int lastIndexOf(Object obj); Returns the last occurrence of obj in the current collection.
  6. Object remove(int index); Removes the element at the specified index location and returns this element.
  7. Object set(int index,Object ele); Set the element at the specified index position to ele, which is equivalent to replacement.
  8. List subList(int fromIndex,int toIndex); Returns a subset from fromindex to toindex. (front closed and rear open)
  9. Three traversal modes of List: ① iterator ② enhanced for loop (the bottom layer is also iterator) ③ ordinary for loop

**Exercise procedure: * * sort the collection according to the book price.

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

public class ListExercise {
    public static void main(String[] args) {
        List list= new ArrayList();

        Book book1=new Book("The Dream of Red Mansion",20);
        Book book2=new Book("Journey to the West",90);
        Book book3=new Book("Romance of the Three Kingdoms",30);
        Book book4=new Book("Water Margin",80);
        list.add(book1);
        list.add(book2);
        list.add(book3);
        list.add(book4);

        Iterator iterator=list.iterator();
        while (iterator.hasNext()){
            Book book=(Book)iterator.next();
            System.out.println(book);
        }

        sort(list);


        System.out.println("-----After sorting-----");
        iterator=list.iterator();
        while (iterator.hasNext()){

            System.out.println(iterator.next());
        }

    }

    public static void sort(List list){
        int size = list.size();
        for (int i = 0; i < size-1; i++) {
            for (int j = 0; j < (size-1-i); j++) {
//                Object book1=list.get(j);// Here, you use object to receive objects, but you can't call the special functions in the Book class
//                Object book2=list.get(j+1);
                Book book1=(Book)list.get(j);
                Book book2=(Book)list.get(j+1);
                if (book1.getBookPrice()>book2.getBookPrice()){
                    list.set(j,book2);
                    list.set(j+1,book1);
                }

            }
        }//End of cycle
    }
}

class Book{
    String bookName;
    double bookPrice;

    public Book(String bookName, double bookPrice) {
        this.bookName = bookName;
        this.bookPrice = bookPrice;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public double getBookPrice() {
        return bookPrice;
    }

    public void setBookPrice(double bookPrice) {
        this.bookPrice = bookPrice;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookName='" + bookName + '\'' +
                ", bookPrice=" + bookPrice +
                '}';
    }
}

Keywords: Java list

Added by 22Pixels on Fri, 17 Sep 2021 16:55:41 +0300