java -- wrapper class, List interface, ArrayList collection

Catalog

Packaging Class

Packing, Unpacking

Comparison of packing

List interface

ArrayList Collection

Traversal of Collection Collections

Iterator Traversal Collection

Delete exception for iterator

ConcurrentModificationException exception for ArrayList collection

The cause of the anomaly

Single-threaded solution--method to call iterator

Multithreaded solution--using CopyOnWriteArrayList

for-each traversal

for loop traversal

Packaging Class

The eight basic types correspond to their respective packaging classes, which include operations on the basic types

For example, int's wrapper class Integer

public static void main(String[] args) {
        int s = Integer.valueOf(3);
        //Equivalent to
        int a = 3;
        System.out.println(s);
        System.out.println(a);
        int str = Integer.valueOf("123");//Converts a string to a number
        System.out.println(str);
    }

Packing, Unpacking

Boxing - Convert common types to packing class types

Unpacking - Converts the packing class type to the normal type

 public static void main(String[] args) {
        Integer s=123;//Packing
        int b=s;//Unpacking

        Integer str=Integer.valueOf(123);//Show packing
        int a=str.intValue();//Show Unboxing
    }

Implicit packing and unpacking are achieved by calling methods.

Comparison of packing

   public static void main(String[] args) {
        Integer a=13;
        Integer b=13;
        System.out.println(a==b);
        Integer c=139;
        Integer d=139;
        System.out.println(c==d);
    }

Implicitly called valueof method

Summary: Integer type data: [-128~127] number from the initialization array compare addresses are the same, out of range new type, address is different

List interface

The List interface inherits the Collection interface, and the List interface elements are duplicated and ordered

The List interface inherits all the abstract methods of the Collection interface and has a few more unique methods

add - - add elements

 public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        //ArrayList class implements List interface, transition up
        list.add("hello");//Add element at end
        list.add(0,"world");//Add at a certain mark
        System.out.println(list);
    }

remove - - delete element

 public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        //ArrayList class implements List interface, transition up
        list.add("hello");//Add element at end
        list.add(0,"world");//Add at a certain mark
        list.add("fine");
        System.out.println(list);

        list.remove("hello");
        list.remove(1);//Remove an element of a subscript
        System.out.println(list);
    }

Get - - get an element of a subscript

  public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        //ArrayList class implements List interface, transition up
        list.add("hello");//Add element at end
        list.add(0, "world");//Add at a certain mark
        list.add("fine");
        System.out.println(list);
        
        String str = list.get(1);//Returns the element of a subscript
        System.out.println(str);
    }

indexOf() - Returns the subscript of the first occurrence of an element

lastIndexOf() - Subscript that appears last in an element

        System.out.println(list.indexOf("world"));
        System.out.println(list.lastIndexOf("world"));;///Return last index occurrence

sort(Comparator<? super E > c) - Sort

class Person{
    int age;
    String name;

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

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}
class Agesort implements Comparator<Person>{
    @Override
    public int compare(Person o1, Person o2) {
        return (o1).age-o2.age;
    }
}
class NameSort implements Comparator<Person>{
    @Override
    public int compare(Person o1, Person o2) {
        return o1.name.compareTo(o2.name);
    }
}
public class Text {
    public static void main(String[] args) {
        List<Person> list = new ArrayList<>();
        list.add(new Person(10, "Zhang San"));
        list.add(new Person(20, "Li Si"));
        list.add(new Person(5, "King Five"));
        System.out.println(list);
        list.sort(new Agesort());
        System.out.println(list);
        System.out.println("==============");
        System.out.println(list);
        list.sort(new NameSort());
        System.out.println(list);
    }
}

subList() - Returns the elements within an interval

  public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        //ArrayList class implements List interface, transition up
        list.add("hello");//Add element at end
        list.add(0, "world");//Add at a certain mark
        list.add("world");
        System.out.println(list);
        
        List list1=list.subList(0,2);//Returns the left closed right open interval of elements within an interval
        System.out.println(list1);
        list1.add("ok");
        System.out.println(list);
    }

Changes to list1 cause changes to lists

This method returns a SubList, which is an internal class in ArrayList.

When this class is called, its construction method is called instead of creating a new class, but referencing the original class, only returning part of it

ArrayList Collection

Sequence table

Construction method

  public static void main(String[] args) {
       ArrayList<String> arrayList=new ArrayList<>();
       //Call a construction method without parameters
        ArrayList<String> arrayList1=new ArrayList<>(20);
        //The initial space of the array is 20
        ArrayList<String> arrayList2=new ArrayList<>(arrayList);
       //The order table is first populated with arrayList
    }

Add - - add elements

Call a parameterless construction method, the underlying array is empty, so that the next element can prove that the add method must be expanded

 public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        System.out.println(arrayList);
    }

Summary: When invoking a construction method without parameters, the array is empty, and when adding elements, the default size is modified to 10, and then the normal 1.5-fold capacity is achieved

remove - - delete element

public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(2);
        list.add(8);
        System.out.println(list);
        list.remove(0);
        System.out.println(list);
    }

Traversal of Collection Collections

Iterator Traversal Collection

The Iterator interface is part of the Java collection framework and is primarily used to traverse elements. Iterator objects are called iterators

 public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        System.out.println(arrayList);
    }

Internally overridden toString method

 public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add(0,"world");
        Iterator<String> stringIterator =arrayList.iterator();
        while(stringIterator.hasNext()){
            String s=stringIterator.next();
            System.out.print(s+" ");
        }
    }

Delete exception for iterator

  public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add(0,"world");
        ListIterator<String> stringIterator =  arrayList.listIterator();
        while(stringIterator.hasNext()){
                stringIterator.remove();
            System.out.print(stringIterator.next()+" ");
        }
    }

To solve this problem: Iterate elements first, then delete, to avoid throwing exceptions multiple times over the same iterator remove

public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add(0,"world");
        Iterator<String> stringIterator =  arrayList.iterator();
        while(stringIterator.hasNext())
            System.out.print(stringIterator.next()+" ");
        System.out.println("\n+++++++++++++++++");
        stringIterator =  arrayList.iterator();
        while(stringIterator.hasNext()) {
         String s= stringIterator.next();
            if(s.equals("world"))
            stringIterator.remove();
        }
        stringIterator =  arrayList.iterator();
        while(stringIterator.hasNext())
            System.out.print(stringIterator.next()+" ");
    }

Iterators also have different implementation classes, each with its own method

ListIterator: ListIterator provides add, set, previous, and other operations on lists based on Iterator.

    public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add(0,"world");
        ListIterator<String> stringIterator =  arrayList.listIterator();
        while(stringIterator.hasNext())
            System.out.print(stringIterator.next()+" ");
        System.out.println("\n+++++++++++++++++");
        stringIterator =  arrayList.listIterator();
        while(stringIterator.hasNext()) {
         String s= stringIterator.next();
            if(s.equals("world"))
            stringIterator.add("hi");//Adds method for listIterator
        }
        stringIterator =  arrayList.listIterator();
        while(stringIterator.hasNext())
            System.out.print(stringIterator.next()+" ");
        System.out.println(arrayList);
    }

ConcurrentModificationException exception for ArrayList collection

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("hello");
        arrayList.add(0, "world");
        ListIterator<String> stringIterator =  arrayList.listIterator();
        while(stringIterator.hasNext()) {
            String s= stringIterator.next();
            if(s.equals("world"))
                arrayList.add(s);//Method to invoke the ArrayList collection
        }
    }

The cause of the anomaly

From the exception information, you can see that the exception occurs in the checkForComodification() method of the Itr class in the ArrayList class

Discovered cause of exception: code changes are not the same number as expected

Called the add method of ArrayList, which internally implements a change to modCount

In the ArrayList collection, modCount exists when a method modifies code to record the number of modifications, and an exception ConcurrentModificationException is thrown when the number of modifications is inconsistent with the expected number of modifications

Single-threaded solution--method to call iterator

There are add s and other methods in the iterator, but there is one more statement: expectedModCount = modCount; Resolved exception

    public static void main(String[] args) {
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("hello");
        arrayList.add(0, "world");
        ListIterator<String> stringIterator =  arrayList.listIterator();
        while(stringIterator.hasNext()) {
            String s= stringIterator.next();
            if(s.equals("world"))
                stringIterator.add(s);
        }
    }

Multithreaded solution--using CopyOnWriteArrayList

CopyOnWriteArrayList is thread-safe and suitable for multithreading

    public static void main(String[] args)  {
        CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
        list.add(2);
        Iterator<Integer> iterator = list.iterator();
        while(iterator.hasNext()){
            Integer integer = iterator.next();
            if(integer==2)
                list.remove(integer);
        }
    }

for-each traversal

 public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add(0,"world");
        for (String s:arrayList
             ) {
            System.out.println(s);
        }
    }

for loop traversal

    public static void main(String[] args) {
        ArrayList<String> arrayList=new ArrayList<>();
        arrayList.add("hello");
        arrayList.add(0,"world");
        for (int i=0;i<arrayList.size();i++)
            System.out.println(arrayList.get(i));
        }

Keywords: Java list

Added by shaundunne on Thu, 03 Feb 2022 20:07:10 +0200