Collection collection in Java (List class collection)

Keywords: Java PHP Javascript Python

1. Differences between sets and arrays

  • As a container, arrays have some inconveniences. They are inconvenient to add, delete and change operations. Arrays can only store the same data type, which can be either a basic data type or a reference data type.Java puts forward the concept of a collection, which is also a container. It can only store references. A collection is not a class, but a collection framework, consisting of many collections.The following is the inheritance system of the Collection collection:

2. Collection Collection

  • Collection is the root interface in the hierarchy and represents a set of objects, also known as collections'elements.This collection is under the java.util package.

Overview of Collection's capabilities (available through API):
Add functionality:
1. boolean add(Object obj): Add an element
2. boolean addAll(Collection c): Add elements of one collection (add all elements of one collection into another)
Delete function:
3. void clear(): Remove all elements
4. boolean remove(Object o): Remove an element
5. boolean removeAll(Collection c): Remove an element of a collection (removing more than one returned true). Remove an element that is the intersection of two collections. Remove failures return false if there are no intersecting elements
Judgement function:
6. boolean contains(Object o): Determine if the set contains the specified element
7. boolean containsAll(Collection c): Determines whether a set contains a specified set element (this set contains all elements in another set before it returns true) [e.g. 1,2,3 containsAll 12=true 1,2,3 containsAll 2,3,4=false]
8. boolean isEmpty(): Determine if the collection is empty
Get functionality:
9. Iterator <E> iterator () (focus), iterators can be considered pointers
Length function:
10, int size(): Number of elements
Intersection function:
[For example, set A intersects set B, and the resulting intersecting elements are in set A.The Boolean value returned indicates whether the A set has changed or not.)
11. boolean retainAll(Collection c): Get the intersection elements of two sets (intersection: elements that both sets have)
Convert a collection to an array:
12,Object[] toArray()

package org.westos.demo3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
public class Collectionaggregate
{
    public static void main(String[] args)
    {
        Collection c=new ArrayList();//A variable of type interface is required, using a subclass that implements the interface, in a polymorphic form
        boolean b = c.add(12);
        boolean b1 = c.add(true);
        boolean b2 = c.add('c');
        boolean b3 = c.add(new Student());
        boolean b4 = c.add(new int[2]);//All return values indicate whether the element was added successfully
        System.out.println(c);//Print the collection and find that the output is elements inside the collection, so the collection must have overridden toString()

        boolean b5 = c.remove(12);//Removes elements from a collection based on the element, returning whether the removal was successful

        Collection c1=new ArrayList();
        c1.add(12);
        c1.add(true);
        System.out.println(c.removeAll(c1));//true
        System.out.println(c);
        //Remove elements from a set (removing more than one returns true), and delete elements is the intersection of two sets
        //Delete failure returns false if there are no intersecting elements

        c.add(1);
        c.add(2);
        c.add(3);
        c.add(4);
        c.add(5);
        c1.add(1);
        c1.add(2);
        c1.add(3);
        c1.add(4);
        c1.add(5);
        System.out.println(c.contains(1));//Determine if the element is included, true
        System.out.println(c.containsAll(c1));//Judging that set C contains c1,false

        c.clear();//Remove all elements

        System.out.println(c.isEmpty());//Determine if the set is empty, true

        System.out.println(c1.size());//Gets the number of elements in the collection, 7

        c.add(1);
        System.out.println(c.retainAll(c1));//Gets the intersection element of two sets (intersection: elements that both sets have), false

        Object[] obj = c1.toArray();//Convert Set to Array
        System.out.println(Arrays.toString(obj));//[12, true, 1, 2, 3, 4, 5]
    }
}
  • About iterators:
    An iterator is a design pattern that traverses and selects objects in a sequence without requiring developers to understand the underlying structure of the sequence (iterators pull access logic from different types of collection classes to avoid exposing the internal structure of the collection to the outside).Iterators are often considered "lightweight" objects because they are cheap to create.
  • Why use iterators?
    Without iterators, access code and the collection itself are tightly coupled, so access logic cannot be separated from the collection class and client code.Client code cannot be reused because different collections correspond to different traversal methods.For Iterator, it always traverses the collection with the same logic, so that the client does not need to maintain the internal structure of the collection itself, and all internal states are maintained by Iterator.
  • Implementation principle:
    The following Iterator implementation based on ArrayList analyzes the principle of Iterator (based on JDK1.8): There is a method iterator() in the ArrayList class, which returns an iterator implementation, where you can see that the implementation class is called Itr, which is an internal class of ArrayList from its source code.Why set the iterator as an internal class because internal classes (whether member internal or local internal) have access to all members of the external class, including private members.
package org.westos.demo3;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class MyTest1
{
    public static void main(String[] args)
    {
        Collection c=new ArrayList();
        c.add(1);
        c.add(2);
        c.add(3);
        c.add(4);
        c.add(5);
        Iterator iterator = c.iterator();//Using this method to obtain an iterator, an iterator whose Iterator interface traverses the Collection set
        while(iterator.hasNext())
        {//Iterators can be thought of as pointers
            System.out.println(iterator.next());//Determine if the next element exists and get and output if it exists
        }
        System.out.println("The iterator output is:"+iterator);//java.util.ArrayList$Itr@1540e19d
        //Printing this iterator will find a dollar sign inside, indicating that the iterator class is internal
    }
}

3. List subinterface

  • Element sequences are ordered (access sequence is consistent), and each element has an index, allowing duplicate elements in the collection.

An overview of the List collection's unique capabilities:
void add(int index,E element): Adds an element at the specified index
E remove(int index): Removing the element at the specified index returns the removed element
E get(int index): Gets the element at the specified index
E set(int index,E element): Change the element at the specified index to return the replaced element instead

package org.westos.demo3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyTest2
{
    public static void main(String[] args)
    {
        List list=new ArrayList();//polymorphic
        list.add("Romance of the Three Kingdoms");
        list.add("Water Margin");
        list.add("Journey to the West");
        list.add(0,"The Dream of Red Mansion");//A unique way to add elements in a List collection, adding elements based on an index
        list.remove("The Dream of Red Mansion");
        list.remove(0);//A unique way to delete elements in a List collection, deleting elements based on an index

        list.add(0);
        list.add(1);
        list.add(2);
        list.add(3);
        list.remove(1);//Here 1 can only represent index, not element 1. Wrap elements if they are indistinguishable or indexed
        list.remove(Integer.valueOf(1));

        System.out.println("The first element in the collection is:"+list.get(0));//A unique way to get elements from an index in a list, noting that the index is out of bounds
        list.set(0,"The Scholars");//Replace elements by index

        System.out.println(list);//[External history of Confucian, 0, 2, 3]
    }
}
  • Several ways to traverse a List collection:
package org.westos.demo3;

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

public class MyTest3
{
    public static void main(String[] args)
    {
        List list = new ArrayList();
        list.add("Broken glaze");
        list.add("Muslim funeral");
        list.add("Lu Xun");
        list.add("Bingxin");
        list.add("Ba Jin");

        //Mode 1;
        Iterator i=list.iterator();
        while(i.hasNext())
        {
            System.out.println(i.next());
        }

        //Mode 2:
        for (int j = 0; j < list.size(); j++)
        {
            System.out.println(list.get(j));
        }

        //Mode 3: The List collection itself has an iterator
        ListIterator listIterator = list.listIterator();
        //The parent interface of this iterator is Iterator, and the methods inside it are richer than those in the parent interface and can iterate backwards.
        while(listIterator.hasPrevious())
        {
            System.out.println(listIterator.previous());
        }
        //Note: When iterating backwards, the forward iteration must be performed first, because iteration is equivalent to a pointer, and note that the forward and backward iteration must be an iterator
    }
}

4. Concurrent modification exception

  • First look at a piece of code:
package org.westos.demo3;

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

public class MyTest4
{
    public static void main(String[] args)
    {
        List list=new ArrayList();
        list.add("C/C++");
        list.add("Java");
        list.add("PHP");
        list.add("JavaScript");
        list.add("Python");
        list.add("Matlab");
        ListIterator iterator=list.listIterator();
        while(iterator.hasNext())
        {
            String str= (String) iterator.next();
            if(str.equals("PHP"))
                list.add("C#");
          //ConcurrentModificationException, where the program will report and modify exceptions
        }
    }
}
  • Why is this an error?
    When we use an iterator to traverse a set, our iterator already knows the number of elements in the set beforehand. Suddenly adding or deleting elements in the iteration process will disrupt the order of the original set, and the iterator will be unable to do so, throwing and modifying exceptions.There are two ways to solve this problem: 1. Use the iterator's own method of adding and deleting elements in the collection 2. Use the for loop to traverse, you can use the collection's own way of adding and deleting, and the modified code is as follows:
package org.westos.demo3;

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

public class MyTest4
{
    public static void main(String[] args)
    {
        List list=new ArrayList();
        list.add("C/C++");
        list.add("Java");
        list.add("PHP");
        list.add("JavaScript");
        list.add("Python");
        list.add("Matlab");

        ListIterator iterator=list.listIterator();
        while(iterator.hasNext())
        {
            String str= (String) iterator.next();
            if(str.equals("PHP"))
                iterator.add("C#");//Solution 1
        }
        System.out.println(list);//[C/C++, Java, PHP, C#, JavaScript, Python, Matlab]

        for (int i = 0; i < list.size(); i++)
        {
            String str= (String) list.get(i);
            if(str.equals("PHP"))
                list.add("C#");//Solution 2
        }
        System.out.println(list);//[C/C++, Java, PHP, C#, JavaScript, Python, Matlab, C#]
    }
}

5. Characteristics of Different Sets

  • List: Array elements are ordered, elements are allowed to repeat, which set to choose, depending on your needs

6. ArrayList Collection

  • The Collection and List interfaces are implemented, and the common methods used under the java.util package are as follows:

1, Boolean add (E): Add the specified element to the end of this list
2. void add(int index, E element): Insert the specified element into the specified location in this list
3. void clear(): Remove all elements from this list
4. Object clone(): Return a shallow copy of this ArrayList instance
5. boolean contains(Object o): Returns true if the list contains the specified element
6. E get(int index): Returns the element at the specified location in this list
6. int indexOf(Object o): Returns the index of the specified element that first appears in this list, or -1 if this list does not contain elements
7. boolean isEmpty(): Returns true if there are no elements in this list
8. int lastIndexOf(Object o): Returns the index of the specified element that last appeared in this list, or -1 if this list does not contain an index
9, E remove(int index): Remove elements at specified locations in this list
10, boolean remove(Object o): Remove the specified element that first appears in this list if it exists
11. protected void removeRange(int fromIndex, int toIndex): Remove all elements in the list indexed between fromIndex (including) and toIndex (excluding)
12, E set(int index, E element): Replace the element at the specified location in this list with the specified element
13, int size(): Returns the number of elements in this list
14, Object[] toArray(): Returns an array containing all elements in this list in the appropriate order (from the first to the last element)

package org.westos.demo3;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;

public class MyTest5
{
    public static void main(String[] args)
    {
        ArrayList a = new ArrayList();
        a.add(100);
        a.add(200);
        a.add(300);
        a.add(100);
        a.add(267);
        a.add(383);
        a.add(157);
        int i = a.indexOf(100);
        System.out.println("Element 100 is in the set a The index in is:"+i);//0
        System.out.println("Element 100 is in the set a The last index to appear is:"+a.lastIndexOf(100));//3

        a.sort(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Integer a= (Integer) o1;
                Integer b= (Integer) o2;
                return a-b;
            }
        });//Sort elements in a collection
        System.out.println("The elements in the collection are:"+a);//[100, 100, 157, 200, 267, 300, 383]

        List list = a.subList(0, 2);
        System.out.println("The set intercepted from the index is:"+list);//[100, 100]

        Object o = a.clone();
        System.out.println("The shallowly cloned elements are:"+o);//[100, 100, 157, 200, 267, 300, 383]

        //JDK1.8 provides an internal iteration for the ArrayList collection
        a.forEach(new Consumer() {
            @Override
            public void accept(Object o) {
                System.out.println(o);
            }
        });
    }
}

Removing duplicate elements from a collection: The requirement is that you cannot create a new container, just remove the duplicate elements from the original collection

package org.westos.demo4;

import java.util.ArrayList;
import java.util.ListIterator;

public class MyTest1
{
    public static void main(String[] args)
    {
        ArrayList list=new ArrayList();
        list.add(100);
        list.add(100);
        list.add(100);
        list.add(100);
        list.add(100);
        list.add(200);
        list.add(300);
        list.add(400);
        list.add(100);
        list.add(200);
        list.add(400);
        list.add(500);
        list.add(100);
        list.add(200);
        list.add(300);
        list.add(400);
        //Mode 1 - - - Principle: Similar to Selective Sorting
        deleteEle(list);

        //Mode 2 -- Recursion
        ArrayList list1=removeEle(list);
        System.out.println(list1);//[500, 100, 200, 300, 400]
    }

    private static ArrayList removeEle(ArrayList list)
    {
        for (int i = 0; i < list.size(); i++)
        {
            if(list.indexOf(list.get(i))!=list.lastIndexOf(list.get(i)))
            {
                list.remove(list.get(i));
                removeEle(list);
            }
        }
        return list;
    }

    private static void deleteEle(ArrayList list)
    {
        for (int i = 0; i < list.size()-1; i++)
        {
            for (int j = i+1; j < list.size(); j++)
            {
                if (list.get(i).equals(list.get(j)))
                {
                    list.remove(j);
                    j--;
                }
            }
        }
        System.out.println(list);//[100, 200, 300, 400, 500]
    }
}

7. Vector Collection

  • The underlying data structure of the Vector collection is still an array, so it is not commonly used because of its fast query speed, slow growth and deletion, thread security, and low efficiency.Here are some of its common methods:

1. Boolean add (E): Add the specified element to the end of this vector
2. void add(int index, E element): Insert the specified element at the specified position of this vector
3. void addElement(E obj): Add the specified component to the end of this vector and increase its size by 1
4. E elementAt(int index): Returns the component at the specified index
5. E firstElement(): Returns the first component of this vector (item at index 0)
6. void removeElementAt(int index): Delete the component at the specified index
7. List <E> SubList (int fromIndex, int toIndex): Returns a partial view of this List with elements ranging from fromIndex (including) to toIndex (excluding)
8. Object[] toArray(): Returns an array containing all elements in this vector in the proper order

package org.westos.demo4;

import java.util.Enumeration;
import java.util.Vector;

public class Vectorclass
{
   public static void main(String[] args)
   {
       Vector vector = new Vector();
       vector.add("aaa");
       vector.addElement("bbb");
       vector.add("ccc");
       vector.add("ddd");
       vector.add("eee");
       vector.add("fff");

       System.out.println(vector.get(0));//aaa
       System.out.println(vector.elementAt(0));//One role--aaa

       System.out.println(vector.firstElement());//aaa
       System.out.println(vector.lastElement());//fff

       //vector.removeAllElements();//Empty all elements

       //Incoming iterators
       Enumeration elements = vector.elements();
       while(elements.hasMoreElements())
       {
           System.out.println(elements.nextElement());
       }
   }
}

8. linkedList Collection

  • The bottom level is a chain table, queries are slow, add or delete quickly, threads are not safe, and efficiency is high

LinkedList class specific features:
Public void addFirst (E): Add elements to the top of the collection
AddLast (E): Add elements to the end of the collection
public E getFirst(): Get the first element
getLast(); takes the second element
public E removeFirst(): Remove the first element
public E removeLast(): Remove the second element

[Case] Please use LinkedList to simulate the collection of stack data structures and test

//Test class:
package org.westos.demo4;

public class MyTest2
{
    public static void main(String[] args)
    {
        //Simulate stack data structure with LinkedList collection, FIFO
        MyList myList=new MyList();
        myList.addEle("abc1");
        myList.addEle("abc2");
        myList.addEle("abc3");
        myList.addEle("abc4");
        myList.addEle("abc5");

        Object obj=myList.getEle();
        System.out.println(obj);

        Object obj1 = myList.getEle();
        System.out.println(obj1);

        System.out.println(myList.toString());//[abc3, abc2, abc1, abc5, abc4]
    }
}
//Tool class:
package org.westos.demo4;

import java.util.LinkedList;

public class MyList
{
    LinkedList list=null;

    public MyList(){
        list=new LinkedList();
    }

    public void addEle(Object obj)
    {
        list.addFirst(obj);
        //list.push(obj); - Add elements to the chain head
    }

    public Object getEle()
    {
        Object o = list.pop();
        //list.addFirst(o); - Your own mistake
        list.addLast(o);//Correct practices
        return o;
    }

    @Override
    public String toString() {
        return list.toString();
    }
}

[Case] ArrayList removes duplicate values of strings in a collection (the contents of strings are the same)

//Existing classes are deduplicated:
package org.westos.demo4;
import java.util.ArrayList;
public class MyTest3
{
    public static void main(String[] args)
    {
        ArrayList list = new ArrayList();
        list.add("aaa");
        list.add("bbb");
        list.add("aaa");
        list.add("ccc");
        list.add("bbb");
        list.add("ddd");
        list.add("bbb");
        list.add("aaa");
        list.add("ccc");
        list.add("bbb");
        list.add("ddd");
        //Remove duplicate elements from a collection
        //Do this by creating a new set
        ArrayList newList = new ArrayList();
        for (int i = 0; i < list.size(); i++)
        {
            Object o = list.get(i);//To reload to a new collection
            if(!newList.contains(o))
            {
                newList.add(o);
            }

        }
        System.out.println(newList);//[aaa, bbb, ccc, ddd]

    }
}
//Custom class de-weighting--
//Test class:
package org.westos.demo4;
import java.util.ArrayList;
public class MyTest4
{
    public static void main(String[] args)
    {
        ArrayList list=new ArrayList();
        list.add(new Student("Zhang San",19));
        list.add(new Student("Li Si",20));
        list.add(new Student("King Five",23));
        list.add(new Student("Zhao Six",18));
        list.add(new Student("Zhang San",19));
        list.add(new Student("King Five",23));

        ArrayList newList = new ArrayList();

        for (int i = 0; i < list.size(); i++)
        {
            Student stu = (Student) list.get(i);
            if(!newList.contains(stu)){
                //To determine if this Student object exists, it must be wrong to write this directly
                //Every time a new object is stored, the contains() method calls equals() when it decides, comparing address values
                //But we override the equlas() and hashCode () of the Student class, and the contains () method calls the overridden equals() method, comparing field values
                newList.add(stu);
            }
        }
        System.out.println(newList);
    }
}
//Custom Student class:
package org.westos.demo4;
import java.util.Objects;
public class Student
{
    private String name;
    private int age;

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

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

    //Rewrite the two methods to compare the fields name and age
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
Thirteen original articles were published. 8 were praised. 384 were visited
Private letter follow

Posted by AnotherQuestion on Wed, 22 Jan 2020 17:08:43 -0800