day19_Collection Systems, list Interfaces, Common Implementation Classes, Iterators, Enhancement for Common Data Structures

Keywords: Java

Difference between sets and arrays

A collection is a container provided in java that can be used to store multiple data.Since sets and arrays are containers, what's the difference between them?

  • The length of the array is fixed.The length of the collection is variable.
  • Arrays can store basic data type values or objects. Collections can only store reference data types. If you want to save basic data types, you need to save the corresponding wrapper classes

Collections are divided into two main series: Collection and Map, which represent a set of objects, and Map, which represents a set of mapping relationships or key-value pairs.

Collection interface

  • The root interface in the Collection hierarchy.Collections represent a set of objects, also known as collections'elements.Some collections allow duplicate elements, while others do not.Some collections are ordered, while others are unordered.JDK does not provide any direct implementation of this interface: it provides more specific subinterface implementations such as Set and List, Queue.This interface is typically used to pass collections and operate on them where maximum universality is required.Objects that create collections, we all use polymorphism
  • Collection <E> is the parent interface for all single-column collections, so some common methods for single-column collections (List s and Sets) are defined in Collection that can be used to manipulate all single-column collections.The methods are as follows:

Add Elements

  • add(E obj): Add an element object to the current collection
  • AddAll (Collection<?Extends E> other: Add all element objects from the other set to the current set, that is, this = this_other

Sample Code

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

public class Demo01 {
    public static void main(String[] args) {
        //Creating Collection Objects in Polymorphic Form
        Collection<String> collection = new ArrayList<>();

        //Add a single element to a collection object
        collection.add("A");
        collection.add("Morning");
        collection.add("Having dinner");
        System.out.println(collection); //[A, morning, meal]

        // All elements of a collection object are added to another collection object
        Collection<String> newCollection = new ArrayList<>();
        newCollection.add("Zhang San");
        newCollection.add("Morning");
        boolean b = newCollection.addAll(collection);   // Return value is added successfully or not
        System.out.println(b); //true

        //The specific implementation class object we created is the ArrayList feature: duplicate objects are allowed
        System.out.println(newCollection);//[Zhang San, Morning, A, Morning, Dining]
    }
}

Delete element

  • boolean remove(Object obj): Deletes the first element found that returns true with the obj object equals from the current collection.
  • Boolean removeAll (Collection<?>Coll: Delete all the same elements from the current collection as the coll collection.That is, this = this - this_coll
  • boolean removeIf(Object o): By removing based on a condition, we can pass a lambda expression to customize the removal condition

Sample Code

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

public class Demo02 {
    public static void main(String[] args) {
        //Creating Collection Objects in Polymorphic Form
        Collection<String> collection = new ArrayList<>();

        //Add a single element to a collection object
        collection.add("A");
        collection.add("Morning");
        collection.add("Having dinner");
        System.out.println(collection); //[A, morning, meal]
        //Delete a single element
        collection.remove("A");
        System.out.println(collection);//[Eat in the morning]


        Collection<String> newCollection = new ArrayList<>();
        newCollection.add("Zhang San");
        newCollection.add("Morning");
        newCollection.add("Li Si");
        newCollection.add("King Five");
        newCollection.add("test");
        // Remove all elements from the current set that are identical to those in the parameter set
        newCollection.removeAll(collection);
        System.out.println(newCollection);  // [Zhang San, Li Si, Wang Wu, test]

        // By removing based on the condition, we can customize the deletion condition by passing a lambda expression
        newCollection.removeIf(
                //Remove element with character length 2
                (String s) -> {
                    return s.length() == 2;
                });

        //The specific implementation class object we created is the ArrayList feature: duplicate objects are allowed
        System.out.println(newCollection);//[test]
    }
}

judge 

  • boolean isEmpty(): Determines if the current collection is empty.
  • boolean contains(Object obj): Determines if there is an element in the current collection that returns true with the obj object equals.
  • Boolean containsAll (Collection<?>c): Determines whether elements in the c set exist in the current set.That is, whether the c set is a "subset" of the current set.

Get the number of elements

  • int size(): Gets the number of elements actually stored in the current collection

intersection

  • Boolean retainAll (Collection<?>Coll: The current set only retains the same elements as those in the coll set, that is, only the intersection of two sets in the current set, that is, this = this_coll;

Convert to Array

  • Object[] toArray(): Returns an array containing all elements in the current collection

Part of the method demonstrates:

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

public class Demo {
    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>();
        // Create collection objects using polymorphism
        Collection<String> coll = new ArrayList<String>();
        // Usage method
        // Add function Boolean add (String s)
        coll.add("Little Li Guang");
        coll.add("Sweeping monk");
        coll.add("Stone breaks the sky");
        System.out.println(coll);//[Xiao Li Guang, Sweeping monk, Stone broken sky]

        // boolean contains(E e) to determine if o exists in the set
        System.out.println("Is the sweeper in a collection:" + coll.contains("Sweeping monk")); //Are sweepers in the collection:

        //Boolean remove (E) deletes o elements in a collection
        System.out.println("Delete Stone Crash:" + coll.remove("Stone breaks the sky"));//Remove Stone Crash:
        System.out.println("Elements in the collection after operation:" + coll);//Elements in collection after operation: [Xiao Li Guang, Sweeping Monk]

        // There are several elements in the size() collection
        System.out.println("There are" + coll.size() + "Elements");//There are two elements in the set

        // Object[] toArray() converted to an Object array
        Object[] objects = coll.toArray();
        // foreach
        for (int i = 0; i < objects.length; i++) {
            System.out.print(objects[i]+"\t"); //Little Li Guang	Sweeping monk	
        }
        System.out.println();
        // Void clear() empty collection
        coll.clear();
        System.out.println("The contents of the collection are:" + coll);//The contents of the collection are: []
        // Boolean isEmpty() to determine if it is empty
        System.out.println(coll.isEmpty());//true
    }
}


 Iterator Iterator

In program development, it is often necessary to iterate through all elements in a collection.For this need, JDK specifically provides an interface, java.util.Iterator.The Iterator interface is also a member of the Java collection, but unlike the Collection and Map interfaces, the Collection and Map interfaces are primarily used to store elements, while the Iterator is primarily used to iteratively access (i.e., traverse) elements in a Collection, so Iterator objects are also known as iterators.

To traverse a Collection set, you need to get the set iterator to complete the iteration. Here's how to get the iterator:

  • public Iterator iterator(): Gets the iterator corresponding to the collection used to iterate through the elements in the collection.

The following describes the concept of iteration:

  • Iteration: A common way to get Collection collection elements.Before you take an element, you must first determine if there is an element in the collection. If there is one, you can take it out, continue to make a judgement, and then take it out if there is one.Always take out all the elements in the collection.This method of removal is termed iteration.

Common methods for the 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 over.

Next, we'll use a case study to learn how to use Iterator to iterate over elements in a set:

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

        // Add element to collection
        coll.add("String Aliens");
        coll.add("love remains");
        coll.add("Dog");
        //ergodic
        //Using iterators to iterate through each set object has its own iterator
        Iterator<String> it = coll.iterator();
        //  Generics refer to data types that iterate over elements
        while(it.hasNext()){ //Determine if there are iteration elements
            String s = it.next();//Get Iterated Elements
            System.out.println(s);
        }
  	}
}

If you continue to use the next method of the iterator while collecting elements, there will be an error that java.util.NoSuchElementException does not have collection elements.

Principle of Iterator Implementation

Iterator iterator objects track elements in a collection internally by pointers as they traverse the collection. To help beginners better understand how the iterator works, the next step is to demonstrate the Iterator object iteration process through a legend:

Before calling Iterator's next method, the iterator's index precedes the first element and points to the first element. When the iterator's next method is called for the first time, the first element is returned, then the iterator's index moves one bit backwards, points to the second element, and returns the second element when the next method is called again.The iterator's index then moves one more bit backward, points to the third element, and so on, until the hasNext method returns false, indicating that the end of the set has been reached and the element traversal terminates. 

Delete elements using Iterator iterator

There is one method in the java.util.Iterator iterator: void remove().So, since Collection already has a remove(xx) method, why does the Iterator iterator provide a delete method?Because of Collection's remove method, it cannot be deleted according to the condition.For example, to delete even numbers from the following set elements

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

public class Demo04 {
    public static void main(String[] args) {
        Collection<Integer> coll = new ArrayList<>();
        coll.add(1);
        coll.add(2);
        coll.add(3);
        coll.add(4);
        // Getting iterator objects from coll set objects
        Iterator<Integer> iterator = coll.iterator();
        while (iterator.hasNext()) {
            //Get the elements in the collection
            Integer integer = iterator.next();
            if (integer % 2 == 0) {
                //To whom, then delete who at this time.
                iterator.remove();
            }
        }
        System.out.println(coll);
    }
}

Do not call Collection's remove(xx) method when iterating using the Iterator iterator, otherwise an exception of java.util.ConcurrentModificationException or an indeterminate behavior will be reported.

Enhance for cycle

Enhanced for loops (also known as for each loop) are advanced for loops that follow JDK1.5 and are designed to traverse arrays and collections.Classes that implement the Iterable interface can use iterators and enhanced for.Can simplify traversal of arrays and collections

Format:

Code Samples

public class MyCollectonDemo1 {
    public static void main(String[] args) {
        ArrayList<String> list =  new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add("d");
        list.add("e");
        list.add("f");

        //1, the data type must be the type of element in a collection or array
        //2,str is just a variable name, representing each element in a collection or array in turn during a loop
        //3,list is the set or array to traverse
        for(String str : list){
            System.out.println(str);
        }
    }
}

Do not use the remove() method of Collection during foreach traversal.Otherwise, either an exception java.util.ConcurrentModificationException is reported or the behavior is uncertain.

Summary:

  • If you need to manipulate index, use a normal for loop
  • Use iterators if elements need to be deleted during traversal
  • If you just want to traverse, use Enhanced for

List interface introduction

The java.util.List interface, which inherits from the Collection interface, is an important branch of single-column collections and habitually refers to objects that implement the List interface as List collections.

List interface features:

  • All elements of a List collection are stored in a linear manner, for example, in the order 11, 22, 33.So in a collection, the elements are stored in the order 11, 22, 33)
  • It is an orderly collection of elements accessed.That is, the order in which elements are stored and removed is guaranteed.
  • It is a collection with an index that allows you to precisely manipulate the elements in the collection (as with the index of an array).
  • Collections can have duplicate elements, and the equals method of the element compares whether or not it is a duplicate element.

The elements in the List collection class are ordered and repeatable.This is like customer service at the bank gate, assigning a serial number to every customer who comes to do business: the first one comes from "Zhang San", and the customer service assigns him 0;The second one was Li Si, which was assigned to him by customer service.By analogy, the last serial number should be "Total number-1".The List collection cares about the ordering of elements and not about repetition, so remember this principle.For example, "Zhang San" can get two numbers.

Common methods in the List interface

As a subinterface of the Collection collection, List not only inherits all the methods in the Collection interface, but also adds some unique methods to manipulate the collection based on the element index, as follows: In addition to the methods inherited from the Collection collection, List adds some methods to manipulate the collection elements based on the index.Common methods are as follows:

Code Samples

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

public class DemoList {
    public static void main(String[] args) {
        // Create List Collection Object
        List<String> list = new ArrayList<String>();

        // Add the specified element to the tail
        list.add("Diagram");
        list.add("Xiaomei");
        list.add("Unhappy");

        System.out.println(list);
        // add(int index,String s) to the specified location
        list.add(1, "Brailless");

        System.out.println(list);
        // String remove(int index) Returns the deleted element by deleting the specified location element
        // Delete element with index position 2
        System.out.println("Delete element with index position 2");
        System.out.println(list.remove(2));
f
        System.out.println(list);

        // String set(int index,String s)
        // Substitute elements at specified locations (change)
        // Modify the specified location element
        list.set(0, "Tritrichoma");
        System.out.println(list);

        // String get(int index) Gets the specified location element

        // Used to traverse with the size() method
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
        //You can also use enhanced for
        for (String string : list) {
            System.out.println(string);
        }
    }

}

There are many implementation classes for the List interface, most commonly:

  • ArrayList: Dynamic Array
  • Vector: Dynamic Array
  • LinkedList: Two-way linked list
  • Stack: Stack

Common data structures

Common structures for data storage are stack, queue, array, chain table, and red-black tree.Let's get to know each other

Stack

Stack: stack, also known as stack, is a linear table with limited operations. Its limitation is that insert and delete operations are allowed only at one end of the target, and add, find, delete operations are not allowed anywhere else.Simply put: With this structured collection, access to elements is characterized by

  • FIFO (that is, the element stored in is removed after it is removed in turn).For example, when a bullet is pushed into the clip, the bullet that is pushed in is below, then the bullet that is pushed in is above. When a gun is fired, the bullet above is first ejected before the bullet below is ejected.The entrance and exit of the stack are at the top of the stack

 Here are two nouns to note:

  • Stack: is to store elements.That is, the elements are stored at the top of the stack, and the existing elements in the stack move one position in turn toward the bottom of the stack.
  • Bullet stack: just take elements.That is, take out the top position element of the stack and move the existing element one position in turn to the top of the stack.

queue

Queue: Queue, or queue for short, is like a stack, a linear table with limited operations that allows insertion only at one end of the table and deletion at the other end of the table.Simply put, using this structured collection, access to elements is characterized by the following:

  • First in, first out (that is, the element stored in, after which the element in front of it is taken out in turn before it is taken out).For example, a small train passes through a cave, with its head in first and its tail in behind.Head out first, tail out.The entrance and exit of the queue are on one side.For example, in the figure below, the left side is the entrance and the right side is the exit.

array

Array: Array is an ordered sequence of elements that opens up a continuous space in memory where elements are stored.It's like a row of rental houses with 100 rooms, each with a fixed number from 001 to 100, so you can quickly find the person who rents the house.

Simply put, using this structured collection, access to elements is characterized by the following:

  • Quick Find Elements: Quick access to elements at specified locations through an index
  • Slow addition and deletion of elements:
    • Specify index position to add elements: You need to create a new array, store the specified new elements in the specified index location, and copy the original array elements to the location of the corresponding index of the new array based on the index.
    • Specify index location to delete elements: You need to create a new array to copy the elements of the original array to the location of the corresponding index of the new array based on the index. The elements of the specified index location in the original array are not copied to the new array.

linked list

Link list: A linked list consists of a series of nodes (each element in the list is called a node), which can be generated dynamically at runtime i.Each node consists of two parts: a data field storing data elements and a pointer field storing the address of the next node.We often talk about the structure of one-way and two-way Chain lists, so here we introduce the one-way chain list.Simply put, using this structured collection, access to elements is characterized by the following:

  • Connect through addresses between multiple nodes.
  • Slow element lookup: To find an element, you need to go back through the connected nodes to find the specified element in turn
  • Fast addition and deletion of elements : Add or remove elements: Simply modify the address connecting the next element.

red-black tree

  • Features of red-black trees: Very fast, approaching the balance tree, finding the minimum and maximum number of leaf elements is not more than twice

ArrayList of the implementation class of the List interface

ArrayList Is List Subclass, Methods in List ArrayList All of them are available, so we won't go into details here. The structure of the java.util.ArrayList collection data store is an array structure.Elements increase or decrease slowly and find quickly. Since the most frequently used function in daily development is to query and traverse data, ArrayList Is the most commonly used collection.Many programmers use ArrayList very freely when developing It is not rigorous to fulfill any need, and this usage is not advocated.

Source characteristics of the ArrayList class:

  • ArrayList is also 10 in JDK1.6 and earlier, while ArrayList after JDK1.7 is initialized to an empty array of length 0, and then an array of length 10 is created when the first element is added.When our underlying array reaches its maximum capacity, ArrayList expands by 1.5 times.Threads are insecure and efficient.

LinkedList of the implementation class of the List interface

LinkedList is a subclass of List. The methods LinkedList in List can be used. This is not explained in detail here. We just need to know the specific methods of LinkedList.The structure of the java.util.LinkedList collection data store is a chain table structure.A collection that facilitates the addition and deletion of elements.Queries are slow and add or delete quickly.Adding and deleting an element of a collection in real development often involves end-to-end operations, whereas LinkedList provides a number of ways to do this.

Unique method:

Posted by kkessler on Fri, 03 Sep 2021 10:02:27 -0700