Java Collection&Iterator

Posted by Gappa on Wed, 03 Nov 2021 22:24:41 +0100

01. java collection overview

1.1 comparison and overview of set framework and array

  • 1. Sets and arrays are structures that store multiple data, referred to as Java containers for short.

    • explain; Storage at this time mainly refers to the storage at the storage level, and does not involve persistent storage (. txt,.jpg,.avi, in the database)
  • 2. Characteristics of the array in storing multiple data covers:

    • Once initialized, its length is determined.
    • Once the array is defined, its data type is determined. We can only operate on the specified type of data.
  • 3. Characteristics of array in storing multiple data:

    • Once initialized, its length cannot be modified.
    • The methods provided in the array are very limited. It is very inconvenient and inefficient to add, delete and insert data.
    • The requirement to obtain the number of actual elements in the array. There are no ready-made properties or methods available in the array
    • The characteristics of array storage data: orderly and repeatable. For disordered and unrepeatable requirements, they cannot be met.

1.2 API s involved in the collection framework

  • Java collections can be divided into Collection and Map systems
    • Collection interface: single column data, which defines the collection of methods to access a group of objects
      • List: an ordered and repeatable collection of elements
      • Set: an unordered and non repeatable set of elements
    • Map interface: double column data, which saves the set with mapping relationship "key value pair"

1. Collection interface inheritance tree

2. Map interface inheritance tree

/*Collection framework
 *       |----Collection Interface----|: Singleton collection, used to store objects one by one
 *           |----list Interface: store ordered and repeatable sequences.  -->"Dynamic array
 *               |----ArrayList,LinkedList,Vector
 *  *           |----set Interface: stores unordered and non repeatable sequences   -->"Assemble“
 *               |----HashSet,LinkedHashSet,TreeSet
 *  *       |----Map Interface----|: Double instance set, used to store a pair of( key-value)A pair of objects  -->Mapping function y=f(x)
 *               |----HashMap,LinkedHashMap,TreeMap,HashTable,Properties
 * /

02. Collection interface method

  • The Collection interface is the parent interface of the List, Set and Queue interfaces. The methods defined in this interface can be used to operate both Set sets and List and Queue sets.
  • JDK does not provide any direct implementation of this interface, but provides more specific implementation of sub interfaces (such as Set and List).
  • Before Java 5, the Java collection will lose the data types of all objects in the container and treat all objects as Object types; after adding generics to JDK 5.0, the Java collection can remember the data types of objects in the container.

2.2 common methods in Collection interface

  • add(Objec tobj): add
  • Add all (collection Coll): add all elements in coll
  • int size(): get the number of valid elements
  • void clear(): clear the collection elements
  • boolean isEmpty(): whether the set is empty
  • boolean contains(Object obj): it is used to judge whether it is the same object through the equals method of the element
  • boolean containsAll(Collection c): it also calls the equals method of elements to compare. Compare the elements of two collections one by one.
  • boolean remove(Object obj): judge whether it is the element to be deleted through the equals method of the element. Only the first element found will be deleted
  • boolean removeAll(Collection coll): take the difference set of the current set
  • Boolean retain all (collection c): save the result of intersection in the current collection without affecting c
  • boolean equals(Object obj): judge whether the sets are equal
  • Object[] toArray(): convert a collection to an array
  • hashCode(): get the hash value of the collection object
  • iterator(): returns an iterator object for collection traversal

03, Iterator iterator interface

  • The Iterator object is called an Iterator (a kind of design pattern) and is mainly used to traverse the elements in the Collection.
  • GOF defines iterator mode as providing a way to access each element in a container object without exposing the internal details of the object. Iterator mode is born for the container, which is similar to "conductor on the bus", "stewardess on the train" and "stewardess".
  • The Collection interface inherits the java.lang.iteratable interface, which has an iterator() method, so all Collection classes that implement the Collection interface have an iterator() method to return an object that implements the Iterator interface.
  • Iterator is only used to traverse collections. Iterator itself does not provide the ability to load objects. If necessary, create an iterator
    Object, there must be an iterated collection.
  • Every time a collection object calls the iterator() method, it gets a new iterator object, and the default cursor is before the first element of the collection.

3.1. Use Iterator to traverse Collection


* The traversal operation of collection elements uses the Iterator iterator interface
* Internal methods: hasNext() and next()
* */

import org.junit.Test;

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

public class IteratorTest {

    public void test(){
        Collection coll=new ArrayList();
        coll.add(new String("tom"));
        coll.add(new Person("Jerry",20));

        //Method 1: not recommended
//        Iterator it=coll.iterator();
//        System.out.println(;
//        System.out.println(;
//        System.out.println(;
//        System.out.println(;
//        System.out.println(;

        //Method 2: not recommended
//        Iterator iterator = coll.iterator();
//        for(int i=0;i<coll.size();i++)
//            System.out.println(;

        //Method 3: recommendation
        Iterator iterator = coll.iterator();    //hasNext(): judge whether the next one exists
            System.out.println(;    //next(): the pointer moves down first and then returns the element
    public void test1(){
        Collection coll=new ArrayList();
        coll.add(new String("tom"));
        coll.add(new Person("Jerry",20));

        Iterator iterator = coll.iterator();
        iterator = coll.iterator();

3.2 implementation principle of Iterator

Topics: Java Container