Chapter VII collection

Posted by rubadub on Sat, 12 Feb 2022 08:13:16 +0100

generic paradigm

Why use generics:

Early Object types can accept any Object type, but in practical use, there will be the problem of type conversion. This hidden danger exists, so Java provides generics to solve this security problem

What is generics:

● generic, i.e. "parameterized type". When referring to parameters, the most familiar thing is to have a formal parameter when defining the method, and then pass the argument when calling this method.

● parameterized type is to parameterize the type from the original specific type, which is similar to the variable parameter in the method. At this time, the type is also defined as the parameter form, and then the specific type is passed in when using / calling

public class Demo<T>{ //T can be any identifier. Common parameters in the form of T, E, K, V, etc. are often used to represent generic private T key// Key the type of this member variable is t, and the type of T is specified externally 
       public Generic(T key) {//The type of generic constructor parameter key is also t, and the type of T is specified externally 
              this.key = key; 
       public T getKey(){ //The return value type of the generic method getKey is t, and the type of T is specified externally 
              return key; 

Type parameters of generic types can only be class types (including custom classes)

A generic type can have more than one type parameter.

If no specific type is defined, the default value is Object

Concept of set

When we need to save a set of elements of the same type, we should use a container to store them. Array is such a case

A container, but once the array is defined, the length cannot be changed. However, in our development practice, we often need to save some variable length arrays

Data collection, so we need some containers that can dynamically increase the length to save our data, and we need to save the data

The logic of may be various, so there are various data structures. The realization of various data structures in Java is what we use

To the collection.

Collective system

Collection interface

Collection interface - defines the method of accessing a group of objects, and its sub interfaces Set and List define the storage method respectively

The data objects in the Set have no order and cannot be repeated

The data objects in the List are sequential and can be repeated

Some methods in the Collection interface:

    add(E e)//Add element
    addAll(Collection<? extends E> c) //Add a custom set to this set
    clear() //Empty collection
    contains(Object o) //Returns true if the stimulus and contain the specified element
    containsAll(Collection<?> c) //Returns true if the collection contains all the elements in the specified collection. 
    isEmpty() //Returns true if the collection does not contain elements. 
    remove(Object o) //Delete an element from the collection
    removeAll(Collection<?> c) //Optionally, delete all elements of the specified collection contained in the specified collection. 
    size() //Number of elements in the collection
    retainAll(Collection<?> c) //; Find the intersection, return true if the collection data changes, and return false if it does not change

List interface and implementation class

List inherits the Collection interface and has three implemented classes

ArrayList: the bottom layer is an array. The query is fast, the deletion is from the middle, and the addition is slow

LinkedList: the bottom layer is a two-way linked list, which is slow to query, deleted from the middle and added quickly

Vector: the bottom layer is an array, which is fast to query, slow to add from the middle, and thread safe


Construction method

ArrayList(); By default, the underlying array is not created. When the first element is added, an array ArrayList(int length) with a length of 10 is created; When creating an object, create an array ArrayList(Collection collection) with a specified length; Construct a subclass that implements the collection interface into an ArrayList

Capacity expansion

         //ArrayList < > () creates an underlying array with a length of 10. When adding elements for the first time, the array is really created
         //ArrayList<String> alist1 = new ArrayList<>(20); 
            add()The process of adding an element to a collection
                  When calling add() to add an element, first check whether the underlying array can fit. If so, add the element directly to the end,
                             If not, a new array will be created and the contents of the original array will be copied
                   size  --->Record the number of elements actually loaded into the array
                   public boolean add(E e) {
                        ensureCapacityInternal(size + 1);  //Check whether the element can be put in
                        elementData[size++] = e;
                        return true;
                        Capacity after putting in - Underlying array length >0 
                  if (minCapacity - elementData.length > 0)
                          grow(minCapacity); Capacity expansion
                   private void grow(int minCapacity) {
                        // overflow-conscious code
                        int oldCapacity = elementData.length;
                        int newCapacity = oldCapacity + (oldCapacity >> 1); The capacity of the new array is 1.5 times
                        if (newCapacity - minCapacity < 0)
                            newCapacity = minCapacity;
                        if (newCapacity - MAX_ARRAY_SIZE > 0)
                            newCapacity = hugeCapacity(minCapacity);
                        // minCapacity is usually close to size, so this is a win:
                         * Array copy,Create a new array,Copy the contents of the original array to the new array
                        elementData = Arrays.copyOf(elementData, newCapacity); 

ArrayList some methods

        //System.out.println(list.get(3));// Query fast, directly return the value of the specified location
        //System.out.println(list.remove(3));// Deletes and returns the value of the specified location
        list.removeIf(new Predicate<String>() {//Condition deletion
            public boolean test(String s) {
                return s.equals("e");//Delete eligible elements
        list.set(0,"W");//Replace the element at the specified location
        list.sort(new Comparator<String>() {//Sort specifies the sort rule
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
        List<String> li =  list.subList(0, 4);//Copy a segment from the original set and return to the new set. The original set remains unchanged

       public class ArrayListChild extends ArrayList{
        public static void main(String[] args) {
        ArrayListChild a = new ArrayListChild();
                      a.removeRange(0, 4);//Used in subclasses of ArrayList

ArrayList traversal method

for loop

Length (array) length() (string) size() (set) it is allowed to delete elements when looping, but we need to pay attention to the relationship between index and set length

for(int i=0;i<alist.size();i++){

It is not allowed to delete elements from a for loop when it is enhanced

for(String s : alist){

Iterator traversal

/*Iterator<String> it =  alist.iterator();  //Returns an iterator object that controls the traversal of elements
                                 String s =;
                 /* ListIterator<String> lit =   alist.listIterator();  
                           //listIterator() can only traverse the implementation classes under the List interface
               ListIterator<String> lit =   alist.listIterator(alist.size());


The LinkedList and ArrayList methods are roughly the same

LinkedList adopts linked list storage mode, which is more efficient when inserting and deleting elements. Query efficiency is relatively slow

        Pass in an index. If the index is less than half of the set, search from the node until the value of this position is found
        If it is greater than half, search from the tail node until the value of this position is found
        LinkedList<String> list = new LinkedList<>();
        System.out.println(list.peek());//Retrieves but does not delete the header (first element) of this list.
        System.out.println(list.pop());//Pop an element from the stack represented by this list.
        list.push("d");//Pushes an element onto the stack represented by this list.
        list.remove();//Retrieve and delete the header (first element) of this list.
        list.remove(3);//Delete the element at the specified position in the list.
        list.set(1,"X");//Replaces the element at the specified location in this list with the specified element.
        System.out.println(list.size());//Returns the number of elements in this list.


The bottom layer is also fast array query and slow addition and deletion in the middle, which is thread safe

          public synchronized(Synchronous lock) boolean add(E e) {
                    ensureCapacityHelper(elementCount + 1);
                    elementData[elementCount++] = e;
                    return true;

Set interface and implementation class

The Set interface inherits the Collection interface

The elements stored in the Set are not repeated, but are out of order. The elements in the Set have no index

HashSet: unordered. The underlying data structure is hash table + linked list

TreeSet: ordered. The underlying data structure is a binary tree (red black tree is a self balancing binary tree)


How to judge whether the values are duplicate when adding a HashSet

hashCode() will be called when adding, and equals() will be called to compare whether the contents are equal when adding. It is necessary to ensure efficiency and security. First call hashCode() to calculate a hash value, which is very fast but unsafe. When the hash values are the same, call equals() method for comparison

        HashSet<Student> set = new HashSet<>();
               Our Student class does not override hashCode() and equals(), which will call methods in Object
     "s".hashCode();//character string. Integer.... These classes override hashCode() to calculate the hash value according to the content contained in the object

Traversal HashSet

The difference between listIterator() and iterator()

listIterator() can only traverse classes that implement the List interface

iterator() traverses list and set

          Enhanced for
           for(Integer it : set){

      //Iterator traversal
      Iterator<Integer> it =  set.iterator();
                Integer n =;
                   // it.remove();
      Stream<Integer> stream =;
      stream.forEach(new Consumer<Integer>(){
            public void accept(Integer t) {


You can sort the elements in the Set collection in a specified way. The stored object must implement the Comparable interface

The underlying data structure of TreeSet is red black tree

Map interface

Three implementation classes



Hashtable (thread safe)


clear();//Delete all mappings from the map (optional)
containsKey(Object key);//Returns true if the mapping contains a mapping for the specified key 
containsValue(Object value);//Returns true if the map maps one or more keys to the specified value 
remove(Object key);//If it exists (from an optional operation), delete a key mapping from the map
get(Object key);//Returns the value mapped to the specified key, or null if the mapping contains a mapping for that key
put(K key, V value);//Optionally, associate the specified value with the specified key in the map
putAll(Map<? extends K,? extends V> m);//Optionally, copy all mappings of the specified map to this map
size();//Returns the number of key value mappings in this map
isEmpty();//Returns true if the map does not contain a key value mapping 
replace(K key, V value);//The entry for the specified key can be replaced only when the target is mapped to a value
keySet();//Returns the Set view of the keys contained in this map
entrySet();//Returns the Set view of the mappings contained in this map
forEach(BiConsumer<? super K,? super V> action);//Perform the given operation on each entry in this map,
Until all entries are processed or the operation throws an exception


The key values of elements in HashMap cannot be repeated. The order of arrangement is not fixed, and a null key can be stored.

The bottom layer of HashMap is hash table + linked list + red black tree

Use the key to calculate the hash value, and then use the hash value to calculate the position of the element in the hash table. When there are elements in the same position, they can be stored in the linked list (zipper method). When the number of elements reaches 8, they can be stored in the red black tree.

The default length of the hash table is 8 and the load factor is 0.75. Each time the capacity expansion mechanism is triggered, the capacity expansion is 1.5 times of the original

        HashMap<String,String> hashMap = new HashMap<>();
        System.out.println(hashMap.containsKey("i"));//Include key
        System.out.println(hashMap.containsValue("i"));//Include value
        System.out.println(hashMap.get("o"));//According to the key search value, the key does not exist and returns null
        hashMap.replace("a","m");//Replace the existing key. If the key does not exist, it cannot be replaced


All elements in the TreeMap maintain a certain fixed order. If you need to get an orderly Map, you should use TreeMap,

The class where the key value is located must implement the Comparable interface


The bottom layer is also the implementation of hash table + linked list (red black tree)

Is thread safe synchronized Stringbuffer,Vector

Similar to HashMap

Collections class


        ArrayList<String>list = new ArrayList<>();
        Collections.addAll(list,"d","b","a");//Add the following elements to the list collection
        int index = Collections.binarySearch(list,"a");//Binary search returns an index of type int
        Collections.swap(list,1,3);//Swap the element in the first position with the element in the third position
        ArrayList<String> list1 = new ArrayList<>();
        Collections.copy(list1,list);//Copy the later set to the previous set and overwrite it. The preceding set elements must be more than the following set elements
            List<Object> list2 = Collections.emptyList();//Returns an empty collection. Data cannot be added
        Collections.fill(list,"b");//Replace all elements in the list set with b
        Collections.replaceAll(list1,"b","c");//Replace all b in list1 with c

Sort the collection of class types

        ArrayList<Student> students = new ArrayList<>();
        Student student1 = new Student("tim",10);
        Student student2 = new Student("tom",13);
        Student student3 = new Student("tony",19);
        Student student4 = new Student("jim",14);
        Student student5 = new Student("tim",10);
        Collections.sort(students, new Comparator<Student>() {
            public int compare(Student o1, Student o2) {
                return o1.getAge()-o2.getAge();

      *   int...n Variable length parameters are essentially an array. There can only be one parameter in a parameter list, which must be placed at the last of the parameter list
      *   [I@15db9742
     public static void test(String name,int...n){

Differences between Collections and Collections

Collection is a collection interface, and Link is a single column interface. Provides a common way to perform basic operations on collections.

Collections is a tool class of collection class, which contains many collection related static methods and cannot be instantiated

Topics: Java Back-end