Collection parent class interface, iterator, for enhancement

What is a collection?

A collection is a container provided in Java that can be used to store multiple data.

The difference between collections and arrays:

1. The length of the array is fixed.

The length of the collection is variable.

2. The array stores elements of the same type and can store basic data type values.

Collections store objects. And the types of objects can be inconsistent. In development, when there are many objects, collections are generally used for storage.

Single column collection frame:

Text summary:

Collection: The root interface of the single-column collection class, used to store a series of elements that comply with certain rules. It has two important sub-interfaces, namely java.util.List and java.util.Set. Among them, List is characterized by orderly elements and repeatable elements. The characteristic of Set is that the elements are unordered and non-repeatable. The main implementation classes of the List interface are java.util.ArrayList and java.util.LinkedList, and the Set interface The main implementation classes are java.util.HashSet and java.util.TreeSet.

Image overview:

The orange boxes are filled with interface types, while the blue boxes are filled with specific implementation classes.

Collection interface:

The collection itself is a tool, which is stored in the java.util package. The Collection interface defines the most common content in the single-column collection framework. Collection is the parent interface of all single-column collections, so some methods common to single-column collections (List and Set) are defined in Collection, and these methods can be used to operate all single-column collections.

Some common methods of Collectin parent interface:

public boolean add(E e): Add the given object to the current collection. (increase)
public void clear(): Clear all elements in the collection.

public boolean remove(E e): Remove the given object from the current collection. (delete)
public boolean contains(E e): Determines whether the current collection contains the given object.
public boolean isEmpty(): Determines whether the current collection is empty. (check)
public int size(): Returns the number of elements in the collection.
public Object[] toArray(): Store the elements in the collection into an array.

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

public class Demo1Collection {
    public static void main(String[] args) {
//Create collection object
    // Use polymorphism
    Collection<String> coll = new ArrayList<String>();
    \t// Instructions
    //Add function boolean add(String s)
    coll.add("Xiao Liguang");
    coll.add("Sweeping Monk");
    coll.add("Shi Potian");
    System.out.println(coll);

    // boolean contains(E e) determines whether o exists in the collection
    System.out.println("Judge whether Sweeping Monk is in the collection" + coll.contains("Sweeping Monk"));

    //boolean remove(E e) deletes the o element in the collection
    System.out.println("Delete Shi Potian:" + coll.remove("Shi Potian"));
    System.out.println("Elements in the collection after operation:" + coll);
    \t
    // size() How many elements are there in the collection?
System.out.println("There are " + coll.size() + " elements in the collection");

// Object[] toArray() converts to an Object array
    Object[] objects = coll.toArray();
    // Traverse the array
    for (int i = 0; i < objects.length; i + + ) {
System.out.println(objects[i]);
}

// void clear() clears the collection
coll.clear();
System.out.println("The content in the collection is: " + coll);
// boolean isEmpty() determines whether it is empty
System.out.println(coll.isEmpty());
}
}

Iterator:

Iterator interface:

Iterator is mainly used to iteratively access (i.e. traverse) the elements in Collection, so the Iterator object is also called an iterator.

If you want to traverse a Collection, you must obtain the iterator of the collection to complete the iteration operation. The following is an introduction to the method of obtaining the iterator: public Iterator iterator(): Get the iterator corresponding to the collection, which is used to traverse the collection. of the elements in

What is iteration:

That is, the general method of obtaining Collection elements. Before taking an element, you must first determine whether there is an element in the set. If there is, take out the element and continue to judge. If there is still one, take it out again. Always remove all elements from the collection. The technical term for this method of extraction is iteration.

Commonly used methods of the Iterator interface are:

public E next(): Returns the next element of the iteration

public boolean hasNext(): Returns true if there are still elements to iterate over.

Method demonstration:

public class IteratorDemo {
  public static void main(String[] args) {
        // Create objects using polymorphism
        Collection<String> coll = new ArrayList<String>();

        //Add elements to the collection
        coll.add("Chuan Chuan Xing Ren");
        coll.add("Tucao Xingren");
        coll.add("Poodle");
        //Traverse
        //Use iterator to traverse each collection object has its own iterator
        Iterator<String> it = coll.iterator();
        // Generic refers to iterating out the data type of the element
        while(it.hasNext()){ //Determine whether there are iteration elements
            String s = it.next();//Get the iterated elements
            System.out.println(s);
        }
  }
}

When fetching collection elements, if there are no elements in the collection and you continue to use the next method of the iterator, a java.util.NoSuchElementException error of no collection elements will occur.

Implementation principle of iterator:

Text summary:

When traversing a collection, first obtain the iterator object by calling the iterator() method of the collection, and then use the hashNext() method to determine whether the next element exists in the collection. If it exists, call the next() method to remove the element. Otherwise, it means that the element has been removed. When the end of the collection is reached, stop traversing elements.

Image overview:

Before calling the next method of Iterator, the index of the iterator is located before the first element and does not point to any element. When the next method of the iterator is called for the first time, the index of the iterator will move backward one bit and point to the first element. element and returns the element. When the next method is called again, the index of the iterator will point to the second element and the element is returned, and so on, until the hasNext method returns false, indicating that the end of the collection has been reached, terminating the collection. Traversal of elements.

Enhance for:

Specifically used to traverse arrays and collections. Its internal principle is actually an Iterator, so during the traversal process, elements in the collection cannot be added or deleted.

Traverse the collection:

The knowledge points of the article match the official knowledge archives, and you can further learn related knowledge. Java skill treeCollectionCollection collection traversal 138337 people are learning the system