Collection and sorting

1.Collection collection

1.1 collective Architecture [memory]

  • Characteristics of set classes

    A storage model with variable storage space is provided, and the stored data capacity can be changed at any time

  • System diagram of collection class

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-iWwe0il1-1628240896269)(img(.png)]

1.2Collection set overview and basic usage [ application ]

  • Collection collection overview

    • Is the top-level interface of a singleton 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)

  • Collection basic usage

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

1.3 common methods of collection [application]

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

1.4 traversal of collection [application]

  • Introduction to iterators
    • Iterator, special traversal mode of collection
    • Iterator 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
  • Traversal of Collection
public class IteratorDemo {
    public static void main(String[] args) {
        //Create collection object
        Collection<String> c = new ArrayList<>();

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

        //Iterator < E > iterator(): returns the iterator of the elements in this collection, which is obtained through the iterator() method of the collection
        Iterator<String> it = c.iterator();

        //Using while loop to improve the judgment and acquisition of elements
        while (it.hasNext()) {
            String s = it.next();
            System.out.println(s);
        }
    }
}

1.5 illustration of collective use steps [understanding]

  • Use steps

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jRRHv4ZB-1628240896271)(img].png)]

1.6 case of Collection - the Collection stores student objects and traverses [application]

  • 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

    • Student class
    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());
            }
        }
    }
    

2.List set

2.1 list set overview and features [memory]

  • 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
  • List set features
    • Indexed
    • Duplicate elements can be stored
    • Element access order

2.2 unique method of list set [application]

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.3 case of the set - the List set stores the student object and traverses the [application]

  • 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

    • Student class

      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 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);
      
              //Iterator pattern 
              Iterator<Student> it = list.iterator();
              while (it.hasNext()) {
                  Student s = it.next();
                  System.out.println(s.getName() + "," + s.getAge());
              }
              
              System.out.println("--------");
      
              //for loop mode
              for(int i=0; i<list.size(); i++) {
                  Student s = list.get(i);
                  System.out.println(s.getName() + "," + s.getAge());
              }
      
          }
      }
      

2.4 concurrent modification exception [ application ]

  • 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

  • Solutions

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

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

2.5 list iterator [application]

  • 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.6 enhanced for loop [application]

  • Define format

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

    public class ForDemo {    public static void main(String[] args) {        int[] arr = {1,2,3,4,5};        for(int i : arr) {            System.out.println(i);        }                System.out.println("--------");        String[] strArray = {"hello","world","java"};        for(String s : strArray) {            System.out.println(s);        }                System.out.println("--------");        List<String> list = new ArrayList<String>();        list.add("hello");        list.add("world");        list.add("java");        for(String s : list) {            System.out.println(s);        }                System.out.println("--------");        //The internal principle is an Iterator iterator / * for (string s: list) {if (s.equals ("world")) {list. Add ("JavaEE"); / / concurrentmodificationexception}} * /}}
    

2.7 set case List set stores student objects and traverses [application] 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

    • Student class

      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 ListDemo {    public static void main(String[] args) {        //Create a list collection object list < student > List = new ArrayList < student > ()// Create student object S1 = new student ("Lin Qingxia", 30); Student S2 = new student ("Maggie Cheung", 35); Student S3 = new student ("Wang Zuxian", 33)// Add students to the set list add(s1);         list. add(s2);         list. add(s3);        // Iterator: 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 method 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());}}}
      

3. Data structure

3.1 stack and queue of data structure [memory]

  • Stack structure

    In and out

  • Queue structure

    First in first out

3.2 array and linked list of data structure [memory]

  • Array structure

    Fast query, slow addition and deletion

  • Queue structure

    Slow query, fast addition and deletion

4. Implementation class of list set

4.1 characteristics of list aggregation subclass [memory]

  • 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

4.2 case of the collection - the ArrayList collection stores student objects and traverses [application] 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

    • Student class

      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 ArrayListDemo {    public static void main(String[] args) {        //Create ArrayList collection object ArrayList < student > array = new ArrayList < student > ()// Create student object S1 = new student ("Lin Qingxia", 30); Student S2 = new student ("Maggie Cheung", 35); Student S3 = new student ("Wang Zuxian", 33)// Add students to the set array add(s1);         array. add(s2);         array. add(s3);        // Iterator: iterator < student > it = array iterator();         while (it.hasNext()) {            Student s = it.next();            System.out.println(s.getName() + "," + s.getAge());        }         System. out. println("--------");        // Normal for: traversal method with index for (int i = 0; I < array. Size(); i++) {            Student s = array.get(i);            System.out.println(s.getName() + "," + s.getAge());        }         System. out. println("--------");        // Enhanced for: the most convenient traversal method for (student s: array) {system. Out. Println (s.getname() + "," + s.getage());}}}
      

4.3 unique function of LinkedList set [application]

  • Unique method

    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

Keywords: Java

Added by alvinchua on Sat, 01 Jan 2022 17:55:19 +0200