API Foundation Day 12

Collection (Continued)

Operations between collections

Sets provide operations such as taking and merging sets, deleting intersection sets, judging inclusion subsets, etc

package collection;

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

/**
 * Operations between collections
 */
public class CollectionDemo4 {
    public static void main(String[] args) {
//        Collection c1 = new ArrayList();
        Collection c1 = new HashSet();//Non repeatable element
        c1.add("java");
        c1.add("c");
        c1.add("c++");
        System.out.println("c1:"+c1);
        Collection c2 = new ArrayList();
        c2.add("android");
        c2.add("ios");
        c2.add("java");
        System.out.println("c2:"+c2);
         /*
            boolean addAll(Collection c)
            Adds all elements in a given collection to the current collection. Returns true if the current collection has changed
         */
        boolean tf = c1.addAll(c2);
        System.out.println(tf);
        System.out.println("c1:"+c1);
        System.out.println("c2:"+c2);

        Collection c3 = new ArrayList();
        c3.add("ios");
        c3.add("c++");
        c3.add("php");
        System.out.println("c3:"+c3);
        /*
            boolean containsAll(Collection c)
            Determines whether the current set contains all elements in a given set
         */
        boolean contains = c1.containsAll(c3);
        System.out.println("Include all elements:"+contains);

        /*
            boolean removeAll(Collection c)
            Deletes the common elements in the current collection and the given collection
         */
        c1.removeAll(c3);
        System.out.println("c1:"+c1);
        System.out.println("c3:"+c3);
    }
}

Traversal of sets

Collection provides a unified way to traverse Collections: iterator mode

Iterator iterator()

This method gets an iterator that traverses the elements of the current collection

java.util.Iterator interface

Iterator interface, which defines the related operations of iterator traversing the collection

Different collections implement an Iterator implementation class for traversing their own elements. We don't need to remember their names. We can regard them as iterators from a polymorphic point of view

The iterator traverses the set by following the steps: ask, take and delete Where deleting elements is not necessary

package collection;

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

/**
 * Collection The interface does not define the operation of obtaining an element separately, because it is not common.
 * However, Collection provides the operation of traversing Collection elements. This operation is a general-purpose operation, regardless of the type of operation
 * Collections support this traversal mode: iterator mode.
 *
 * Iterator iterator()           die((second sound)
 * This method gets an iterator that traverses the elements of the current collection
 *
 * java.util.Iterator Interface is an iterator interface, which specifies the relevant operations of iterator traversing the set. Different
 * We don't need to iterate over the elements of the collection until we provide a name for their own implementation
 * The polymorphic method can be used as an Iterator.
 * The iterator traverses the collection in the following steps: ask - > get - > delete
 * Deletion is not required.
 *
 */
public class IteratorDemo {
    public static void main(String[] args) {
        Collection c = new ArrayList();
        c.add("one");
        c.add("two");
        c.add("three");
        c.add("four");
        c.add("five");
        System.out.println(c);
        //Get iterator
        Iterator it = c.iterator();
        /*
            Related methods provided by iterators:
            boolean hasNext()
            Determine whether there are elements in the collection that can be traversed

            E next()
            Get the next element of the collection (get the first element when calling for the first time, and so on)
         */
        while(it.hasNext()){
            String str = (String)it.next();
            System.out.println(str);         
        }
        System.out.println(c);

    }
}

During iterator traversal, elements cannot be added or deleted through the method of collection

package collection;

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

/**
 * Collection The interface does not define the operation of obtaining an element separately, because it is not common.
 * However, Collection provides the operation of traversing Collection elements. This operation is a general-purpose operation, regardless of the type of operation
 * Collections support this traversal mode: iterator mode.
 *
 * Iterator iterator()           die((second sound)
 * This method gets an iterator that traverses the elements of the current collection
 *
 * java.util.Iterator Interface is an iterator interface, which specifies the relevant operations of iterator traversing the set. Different
 * Collections provide an iterator implementation class for traversing their own elements, but we don't need to go up to their names to
 * The polymorphic method can be used as an Iterator.
 * The iterator traverses the collection in the following steps: ask - > get - > delete
 * Deletion is not required.
 *
 */
public class IteratorDemo {
    public static void main(String[] args) {
        Collection c = new ArrayList();
        c.add("one");
        c.add("#");
        c.add("two");
        c.add("#");
        c.add("three");
        c.add("#");
        c.add("four");
        c.add("#");
        c.add("five");
        System.out.println(c);
        //Get iterator
        Iterator it = c.iterator();
        /*
            Related methods provided by iterators:
            boolean hasNext()
            Determine whether there are elements in the collection that can be traversed

            E next()
            Get the next element of the collection (get the first element when calling for the first time, and so on)
         */
        while(it.hasNext()){
            String str = (String)it.next();
            System.out.println(str);
            if("#".equals(str)){
                /*
                    The iterator requires that elements cannot be added or deleted through the collection method during traversal
                    Otherwise, an exception will be thrown: ConcurrentModificationException
                 */
//                c.remove(str);
                /*
                    The remove method of the iterator can remove the elements obtained through the next method from the collection
                    Delete from.
                 */
                it.remove();
            }
        }
        System.out.println(c);

    }
}

Enhanced for loop

JDK5 introduced a feature: enhanced for loop

  • Also known as a new loop, it allows us to use the same syntax to traverse a collection or array

  • Syntax:

    for(Element type variable name : Collection or array){
        Circulatory body
    }
    package collection;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    
    /**
     * JDK5 When it was introduced, a new feature was introduced: enhanced for loop
     * Also known as a new loop, it can traverse a collection or array with the same syntax.
     *
     * The new loop is recognized by the java compiler, not a virtual machine.
     */
    public class NewForDemo {
        public static void main(String[] args) {
            String[] array = {"one","two","three","four","five"};
            for(int i=0;i<array.length;i++){
                String str = array[i];
                System.out.println(str);
            }
    
            for(String str : array){
                System.out.println(str);
            }
    
    
            Collection c = new ArrayList();
            c.add("one");
            c.add("two");
            c.add("three");
            c.add("four");
            c.add("five");
            //Iterator traversal
            Iterator it = c.iterator();
            while(it.hasNext()){
                String str = (String)it.next();
                System.out.println(str);
            }
            //New loop traversal
            for(Object o : c){
                String str = (String)o;
                System.out.println(str);
            }
    
        }
    }

    generic paradigm

    Another feature introduced after JDK5: generics

    Generics, also known as parameterized types, allow us to specify the type of property, method parameter or return value in a class when using it

    • Generics are widely used in collections to specify the types of elements in a collection

    • If a class with generic support does not specify the specific type of generic, it defaults to the prototype Object

      package collection;
      
      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.Iterator;
      
      /**
       * JDK5 When it was introduced, a new feature was introduced: enhanced for loop
       * Also known as a new loop, it can traverse a collection or array with the same syntax.
       *
       * The new loop is recognized by the java compiler, not a virtual machine.
       */
      public class NewForDemo {
          public static void main(String[] args) {
              String[] array = {"one","two","three","four","five"};
              for(int i=0;i<array.length;i++){
                  String str = array[i];
                  System.out.println(str);
              }
      
              for(String str : array){
                  System.out.println(str);
              }
      
              /*
               *  Another feature introduced after generic JDK5.
               * Generics, also known as parameterized types, allow us to specify the type of attributes in a class when using it,
               * The type of method parameter or return value makes us more flexible when using a class.
               * Generics are widely used in collections to specify the types of elements in a collection.
               * If a generic type is not specified when using a class that supports generics, the default is the prototype Object
               *
               * Collection Definition of interface
               * public interface Collection<E> ... {
               *
               * Collection<E> The < E > here is generic
               *
               * Collection The definition of the add method in. The parameter is E
               * boolean add(E e)
               */
              Collection<String> c = new ArrayList<>();
              c.add("one");//The compiler checks whether the argument of the add method is of type String
              c.add("two");
              c.add("three");
              c.add("four");
              c.add("five");
      //        c.add(123);// Compilation failed
              //Iterator traversal
              //Iterators also support generics, and the specified is consistent with the generics specified by the set they traverse
              Iterator<String> it = c.iterator();
              while(it.hasNext()){
                  //When the compiler compiles the code, it supplements the modeling code according to the generics specified by the iterator
                  String str = it.next();//You do not need to be in the shape when getting elements
                  System.out.println(str);
              }
              //New loop traversal
              for(String str : c){
                  System.out.println(str);
              }
      
          }
      }

      List set

    • java.util.List interface, inherited from Collection

      The List set is repeatable and ordered, and provides a set of methods that can manipulate elements through subscripts

      Common implementation classes:

      • java.util.ArrayList: array is used internally to achieve better query performance

      • java.util.LinkedList: the linked list is used internally, and the performance of adding and deleting elements at the beginning and end is better

List collection common methods

get() and set()

package collection;

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

/**
 *  List aggregate
 *  List Collection is a common type of collection under collection.
 *  java.util.List Interface is the interface of all lists, which inherits from Collection.
 *  Common implementation classes:
 *  java.util.ArrayList:The internal is realized by array, and the query performance is better.
 *  java.util.LinkedList:The internal is realized by linked list, and the addition and deletion performance is better.
 *
 *  List The feature of a set is that it can store repeated elements and is orderly. It provides a set of Subscripts
 *  Methods of manipulating elements.
 */
public class ListDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
//        List<String> list = new LinkedList<>();

        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");

        /*
            E get(int index)
            Gets the element corresponding to the specified subscript
         */
        //Get the third element
        String e = list.get(2);
        System.out.println(e);

        for(int i=0;i<list.size();i++){
            e = list.get(i);
            System.out.println(e);
        }

        /*
            E set(int index,E e)
            Set the given element to the specified position, and the return value is the original element of the position.
            Replace element operation
         */
        //[one,six,three,four,five]
        String old = list.set(1,"six");
        System.out.println(list);
        System.out.println("The element to be replaced is:"+old);
    }
}

Overloaded add() and remove()

package collection;

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

/**
 * List Collection provides a pair of overloaded add and remove methods
 */
public class ListDemo2 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");
        System.out.println(list);
        /*
            void add(int index,E e)
            Inserts the given element into the specified location
         */
        //[one,two,six,three,four,five]
        list.add(2,"six");
        System.out.println(list);

        /*
            E remove(int index)
            Deletes and returns the element at the specified location
         */
        //[one,six,three,four,five]
        String e = list.remove(1);
        System.out.println(list);
        System.out.println("Deleted element:"+e);
    }
}

subList() method

package collection;

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

/**
 *  List subList(int start,int end)
 *  Gets a subset of the specified range in the current collection. The two parameters are the subscripts of the beginning and end (including the head but not the tail)
 */
public class ListDemo3 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<10;i++){
            list.add(i);
        }
        System.out.println(list);
        //Get section 3-7
        List<Integer> subList = list.subList(3,8);
        System.out.println(subList);
        //Expand each element of the subset 10 times
        for(int i=0;i<subList.size();i++){
            subList.set(i,subList.get(i) * 10);
        }
        //[30,40,50,60,70]
        System.out.println(subList);
        /*
            The operation on the elements of the subset is the operation on the corresponding elements of the original set
         */
        System.out.println(list);

        //Delete 2-8 in the list set
        list.subList(2,9).clear();
        System.out.println(list);

    }
}

Conversion of set and array

Convert collection to array

Collection provides a method: toArray, which can convert the current collection into an array

package collection;

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

/**
 * Convert collection to array
 * Collection The method toArray is provided to convert the current collection into an array
 */
public class CollectionToArrayDemo {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");
        System.out.println(list);

//        Object[] array = list.toArray();
        /*
            The overloaded toArray method requires an array to be passed in, and all elements of the collection will be stored in the array
            If the len gt h of the array is >, the array will be returned. If the given array is not long enough,
            Then the method will create an array with the same length as the collection size according to the given array type, and
            Return after storing the collection elements.
         */
        String[] array = list.toArray(new String[list.size()]);
        System.out.println(array.length);
        System.out.println(Arrays.toString(array));
    }
}

Variable length parameter

Another feature introduced in JDK5: variable length parameter

Only one variable length parameter can be declared in a method, and it must be the last parameter

package collection;

import java.util.Arrays;

public class ArgDemo {
    public static void main(String[] args) {
        dosome(1,"a");
        dosome(1,"a","b");
        dosome(1,"a","b","a","b","a","b","a","b","a","b");
        dosome(1,new String[]{"1","2","3"});
    }

    public static void dosome(int i,String... s){
        /*
            Variable length parameter is actually an array in a method Several parameters were passed in for the variable length parameter
            The length of the array is consistent with the number of arguments
         */
        System.out.println(s.length);
        System.out.println("s:"+ Arrays.toString(s));
    }

}

Convert array to List collection

Array tool class Arrays provides a static method asList(), which can convert an array into a List collection

package collection;

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

/**
 * Convert array to List collection
 * The arrayslist tool provides a method to convert the static array into an array collection.
 */
public class ArrayToListDemo {
    public static void main(String[] args) {
        String[] array = {"one","two","three","four","five"};
        System.out.println(Arrays.toString(array));
        List<String> list = Arrays.asList(array);
        System.out.println(list);

        list.set(1,"six");
        System.out.println(list);
        //The array changed. Note: the element operation on the set of array conversion is the operation corresponding to the original array
        System.out.println(Arrays.toString(array));

        /*
            Because the array is of fixed length, the operation of adding or deleting elements to the collection is not supported and will be thrown
            Exception: Java lang.UnsupportedOperationException
         */
//        list.add("seven");

        /*
            If you want to add or delete a set, you need to create a set yourself, and then add the set element
            Import.
         */
//        List<String> list2 = new ArrayList<>();
//        list2.addAll(list);
        /*
            All collections support a construction method with the parameter Collection, which is used to create the current Collection
            A collection contains all the elements in a given collection at the same time
         */
        List<String> list2 = new ArrayList<>(list);
        System.out.println("list2:"+list2);
        list2.add("seven");
        System.out.println("list2:"+list2);
    }
}

Keywords: Java Back-end

Added by leo.bonnafe on Sat, 19 Feb 2022 19:15:33 +0200