Together, let's go to the Java collection world to find out—— Collection & List

Keywords: Java list set

catalogue

preface

1, Collection collection

1. Collection characteristics and architecture

2.Collection collection overview and basic usage

3. Common methods and traversal of collection

4. Collection case - the collection stores student objects and traverses them

2, List collection

1.List set overview, features and unique methods

2. Concurrent modification exception

3. List iterator and enhanced for loop

4. Set case - List sets store student objects in three ways

5. Implementation class of list set

preface

        Assemble! Assemble! Let's go to the Java collection world to find out.

        Everyone who studies Java should have learned array. I believe everyone has found that there is a great disadvantage in using array to store data in practical application, that is, its length (storage capacity) is fixed. This will greatly limit the storage of data, because the data is often dynamic in actual development, and the data may be added or deleted at any time. Aiming at this disadvantage of array, Java provides a new type of data storage - collection.

1, Collection collection

1. Collection characteristics and architecture

    1) Set class characteristics

        It provides a storage model with variable storage space, and the stored data capacity can be changed at any time (this is one of the biggest differences between sets and arrays).

    2) System diagram of collection class

        The above is the system diagram of the entire Collection class of Java. This blog only shares the Collection and List collections, and the Set and Map collections will be shared in subsequent blogs.

2.Collection collection overview and basic usage

    1) Collection collection overview

  • Is the top-level interface of a single column Collection. It represents a set of objects, which are also called Collection elements

  • JDK does not provide any direct implementation of this interface. It provides more specific implementation of sub interfaces (such as Set and List)

    2) Collection basic usage

    The following is a code example for the basic use of the Collection:

public class CollectionDemo01 {
    public static void main(String[] args) {
        //Create an object for the Collection
        Collection<String> c = new ArrayList<String>();

        //Add element: Boolean add (E)
        c.add("hello");
        c.add("world");
        c.add("java");

        //Output collection object
        System.out.println(c);
    }
}

3. Common methods and traversal of collection

    1) Collection collection common methods

Method nameexplain
boolean add(E e)Add element
boolean remove(Object o)Removes the specified element from the collection
void clear()Empty elements in collection
boolean contains(Object o)Determines whether the specified element exists in the collection
boolean isEmpty()Determine whether the collection is empty
int size()The length of the set, that is, the number of elements in the set

    2) Traversal of Collection

    Introduction to iterators

  • Iterator, special traversal mode of collection

  • Iterator < E > iterator(): returns the iterator of the elements in this collection, which is obtained through the iterator() method of the collection

  • The iterator is obtained through the iterator() method of the collection, so we say that it depends on the collection

4. Collection case - the collection stores student objects and traverses them

    ① Case requirements

         Create a collection of student objects, store 3 student objects, and use the program to traverse the collection on the console.

    ②   code implementation

    Students:

public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    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;
    }
}

    Test class:

public class CollectionDemo {
    public static void main(String[] args) {
        //Create Collection collection object
        Collection<Student> c = new ArrayList<Student>();

        //Create student object
        Student s1 = new Student("Lin Qingxia", 30);
        Student s2 = new Student("Zhang Manyu", 35);
        Student s3 = new Student("Wang Zuxian", 33);

        //Add students to collection
        c.add(s1);
        c.add(s2);
        c.add(s3);

        //Traversal collection (iterator mode)
        Iterator<Student> it = c.iterator();
        while (it.hasNext()) {
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());
        }
    }
}

        Through the simple sharing of the Collection above, you should initially feel the power of the Collection? Next, we continue to explore the Collection world and share the List Collection with you.

2, List collection

1.List set overview, features and unique methods

    1) List collection overview

  • An ordered set (also known as a sequence), in which the user can accurately control the insertion position of each element in the list. Users can access elements through integer indexes and search for elements in the list

  • Unlike Set collections, lists usually allow duplicate elements

    2) List set features

  • Indexed

  • Duplicate elements can be stored

  • Element access order

    3) List collection specific methods

Method namedescribe
void add(int index,E element)Inserts the specified element at the specified location in this collection
E remove(int index)Deletes the element at the specified index and returns the deleted element
E set(int index,E element)Modify the element at the specified index and return the modified element
E get(int index)Returns the element at the specified index

2. Concurrent modification exception

    1) Causes of occurrence

        In the process of iterator traversal, the elements in the collection are modified through the collection object, resulting in the inconsistency between the expected modified value and the actual modified value in the element obtained by the iterator: ConcurrentModificationException.

    2) Solutions

        Use the for loop to traverse, and then use the collection object to do the corresponding operation.

    3) Sample code

public class ListDemo {
    public static void main(String[] args) {
        //Create collection object
        List<String> list = new ArrayList<String>();

        //Add element
        list.add("hello");
        list.add("world");
        list.add("java");

        //Traverse the collection to get each element. See if there is a "world" element. If so, I will add a "javaee" element. Please write code to implement it
//        Iterator<String> it = list.iterator();
//        while (it.hasNext()) {
//            String s = it.next();
//            if(s.equals("world")) {
//                list.add("javaee");
//            }
//        }

        for(int i=0; i<list.size(); i++) {
            String s = list.get(i);
            if(s.equals("world")) {
                list.add("javaee");
            }
        }

        //Output collection object
        System.out.println(list);
    }
}

3. List iterator and enhanced for loop

    1) List iterator

    > Introduction to listiterator

  • It is obtained through the listIterator() method of the List collection, so it is a unique iterator of the List collection

  • A list iterator that allows the programmer to traverse in either direction, modify the list during the iteration, and get the current position of the iterator in the list

    > Sample code

public class ListIteratorDemo {
    public static void main(String[] args) {
        //Create collection object
        List<String> list = new ArrayList<String>();

        //Add element
        list.add("hello");
        list.add("world");
        list.add("java");

        //Get list iterator
        ListIterator<String> lit = list.listIterator();
        while (lit.hasNext()) {
            String s = lit.next();
            if(s.equals("world")) {
                lit.add("javaee");
            }
        }

        System.out.println(list);

    }
}

    2) Enhanced for loop

    > Define format

for(Element data type variable name : array/Collection object name) {
    Circulatory body;
}

4. Set case - List sets store student objects in three ways

    ① Case requirements

        Create a collection of student objects, store 3 student objects, and use the program to traverse the collection on the console.

    ②   code implementation

         The student class is relatively simple, so I won't show it. I'll look at the test class directly.

    Test class:

public class ListDemo {
    public static void main(String[] args) {
        //Create a List collection object
        List<Student> list = new ArrayList<Student>();

        //Create student object
        Student s1 = new Student("Lin Qingxia", 30);
        Student s2 = new Student("Zhang Manyu", 35);
        Student s3 = new Student("Wang Zuxian", 33);

        //Add students to collection
        list.add(s1);
        list.add(s2);
        list.add(s3);

        //Iterators: Collection specific traversal
        Iterator<Student> it = list.iterator();
        while (it.hasNext()) {
            Student s = it.next();
            System.out.println(s.getName()+","+s.getAge());
        }
        System.out.println("--------");

        //Normal for: traversal with index
        for(int i=0; i<list.size(); i++) {
            Student s = list.get(i);
            System.out.println(s.getName()+","+s.getAge());
        }
        System.out.println("--------");

        //Enhanced for: the most convenient traversal method
        for(Student s : list) {
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

5. Implementation class of list set

    1) Characteristics of List set subclass

    > ArrayList collection

         The bottom layer is the implementation of array structure, with fast query and slow addition and deletion

    > LinkedList collection

         The bottom layer is the implementation of linked list structure, with slow query and fast addition and deletion

    2) Features unique to the LinkedList collection

    Unique methods:

Method nameexplain
public void addFirst(E e)Inserts the specified element at the beginning of the list
public void addLast(E e)Appends the specified element to the end of this list
public E getFirst()Returns the first element in this list
public E getLast()Returns the last element in this list
public E removeFirst()Removes and returns the first element from this list
public E removeLast()Removes and returns the last element from this list

        Well, let's share Collection and List here. We'll see you next time and continue to explore the Collection world of Java. Bye!

ps: it's not easy for bloggers to create. Let's give some praise to the friends who like this article! (#^.^#)

Posted by garfx on Fri, 22 Oct 2021 04:53:20 -0700