Java collection

Posted by CFennell on Mon, 27 Dec 2021 06:22:58 +0100

[Han Shunping talks about Java] Java collection topic - ArrayList HashMap HashSet List Map TreeMap

01 --- understanding and benefits of collection

  1. You can dynamically save any number of objects, which is more convenient.
  2. Provides a series of methods to manipulate objects: add(), remove(), set(), get().

02 ---- framework system of collection

  • Single column set
  • Two column set

[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 cotmtiea-1640566300154) (E: [hanshunping] Java collection \ notes \ 01.png)]

03 --- common methods of collection

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

public class CollectionMethod {

    public static void main(String[] args) {
        List list = new ArrayList();
        //Add add element
        list.add("jack");
        list.add(10);
        list.add(true);
        //remove delete element
        list.remove(0); //Delete first element
        list.remove(true);
        System.out.println(list);
        //contains finds whether the element exists
        System.out.println(list.contains("jack"));
        //size gets the number of elements
        System.out.println(list.size());
        //isEmpty determines whether it is empty
        System.out.println(list.isEmpty());
        //Clear clear
        list.clear();
        //addAll add multiple elements
        List list2 = new ArrayList();
        list2.add("wang");
        list2.add(100);
        list.addAll(list2);
        //cintainsAll finds whether multiple elements exist
        list.containsAll(list2);
        //removeAll deletes multiple elements
        list.removeAll(list2);

    }
}

04 --- iterator traversal

iterator.hasNext(): judge whether there is a next element.

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

public class CollectionIterator {

    public static void main(String[] args) {

        ArrayList arrayList = new ArrayList();
        arrayList.add("Wang");
        arrayList.add("Zhao");
        arrayList.add("Qian");
        //generator iterator 
        Iterator iterator = arrayList.iterator();
		
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}

05 --- enhanced for loop

The underlying enhancement is still an iterator.

for(Object obj : arrayList){
		System.out.println(obj);
}

07 --- list interface method

  1. Orderly and repeatable (add and take out in the same order)
  2. Support index
  3. The elements in the container can be accessed according to the sequence number
  4. ArrayList thread is unsafe and efficient
  5. Vector thread safe
  6. LinkedList thread unsafe

add(int index, Object ele): inserts an ele element at the index position

Add all (int index, collection ELES): add all elements in eles from the index position

get(int index): gets the element at the specified location

indexOf(Object obj): returns the location where obj first appears

lastIndexOf():

remove(int index): deletes the element at the specified location and returns this element

set(int index, Object ele): sets the element at the specified position to ele

subList(int fromIndex, int toIndex): returns a subset from fromIndex to toIndex

12 --- ArrayList underlying structure and source code analysis

  1. ArrayList maintains an array of Object type elementData, transient Object[] elementData.
  2. When creating an ArrayList object, if a parameterless constructor is used, the initial elementData capacity is 0. When adding data for the first time, the expanded elementData is 10. If it needs to be expanded again, increase it by 1.5 times.
  3. When a constructor with a specified size is used, the initial elementData capacity is the specified size. If the capacity needs to be expanded, it shall be increased by 1.5 times.

16 --- vector underlying structure and source code analysis

  1. Vector maintains an array of Object type elementData, transient Object[] elementData.
  2. When creating a Vector object, if you use a parameterless constructor, the default elementData capacity is 10. If you need to expand the capacity, increase it by 2 times.
  3. When a constructor with a specified size is used, the initial elementData capacity is the specified size. If the capacity needs to be expanded, it shall be increased by 2 times.

17 --- LinkedList underlying structure and source code analysis

-Underlying operating mechanism of LinkedList

  1. The underlying LinkedList maintains a two-way linked list
  2. Two attributes are maintained. first and last point to the head node and tail node respectively
  3. The Node object of each Node maintains three attributes: prev, next and item. Prev points to the previous Node and next points to the next Node. Finally, a two-way linked list is realized
  4. Therefore, the addition and deletion of LinkedList elements are not completed through arrays, which is relatively efficient

20 --- Set interface and common methods

  1. Unordered and unrepeatable
  2. No index

21----HashSet

  1. HashSet implements the Set interface
  2. HashSet is actually a HashMap
  3. null values can be stored, but there can only be one
  4. HashSet does not guarantee that the elements are ordered. It depends on the hash before determining the index result
  5. Element, object cannot be repeated
Classic Java interview questions:
Set set = new HashSet();

set.add(new Dog("tom"));	//Ok
set.add(new Dog("tom"));	//Ok

set.add(new String("hsp"));	//Ok
set.add(new String("hsp"));	//false

22 ---- array linked list simulation

Node[] table = new Node[16];

Node john = new Node("john", null);
table[2] = john;
Node jack = new Node("jack", null);
john.next = jack;	//After jack mounts to john

class Node{
    Object item;
    Node next;	//Unidirectional linked list
    public Node(Object item, Node next){
        this.item = item;
        this.next = next;
    }
}

23 --- HashSet capacity expansion mechanism

  • Analyze how the bottom layer of added elements of HashSet is implemented (hash()+equals())

    1. The bottom layer of HashSet is HashMap
    2. When adding an element, first get the hash value, and then convert it to the index value
    3. Find the storage data table table and see if there are elements stored in the index value position
    4. If not, deposit directly
    5. If yes, call equals for comparison. If it is the same, discard the addition. If it is different, add it backward
    6. In Java 8, if the number of elements in a linked list exceeds the default 8 and the size of the table is greater than or equal to the default 64, it will be trealized (red black tree)
  • Analyze the mechanism of HashSet expansion and transformation into red black tree

    1. The bottom layer of HashSet is HashMap. When it is added for the first time, the table array is expanded to 16, and the critical value is 16 * 0.75 (loading factor) = 12
    2. If the table array reaches the critical value of 12, it will be expanded to 16 × 2 (2x expansion) = 32, the new critical value is 24, and so on
    3. In Java 8, only when the number of elements in a linked list exceeds the default 8 and the size of the table is greater than or equal to the default 64, can the tree be made (red black tree). Otherwise, the array expansion mechanism is still used
  • Why is the loading factor 0.75?

    1. The larger the loading factor, the greater the data density of the hash table, the higher the probability of collision, and the longer the linked list in the array (table), resulting in an increase in the number of comparisons during query or insertion and a decline in performance.
    2. The smaller the loading factor, the easier it is to trigger capacity expansion, and the smaller the data density, which means that the smaller the probability of collision, the shorter the linked list in the array, the smaller the number of comparisons during query and insertion, and the higher the performance. But it will waste some memory space. Moreover, frequent capacity expansion will also affect performance.
    3. The source code includes: ideally, using random hash codes, the frequency of nodes in the hash bucket follows the Poisson distribution. When there are 8 elements in the bucket, the probability has become very small, that is to say, it is almost impossible to use 0.75 as the loading factor, and the length of the linked list at each collision location exceeds 8.

28 --- HashSet best practice

import java.util.HashSet;
import java.util.Objects;

public class HashSetExc {
    public static void main(String[] args) {

        HashSet hashSet = new HashSet();
        hashSet.add(new Employee("milan",18));
        hashSet.add(new Employee("jackie",28));
        hashSet.add(new Employee("milan",18));
        // If the equals method is not overridden, three different objects can be added
        // After rewriting, objects with the same name and age are regarded as the same object, and the third object cannot be added
        System.out.println("hashSet == "+ hashSet);
    }

}

class Employee{
    private String name;
    private int age;

    public Employee() {
    }

    public Employee(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;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return age == employee.age && Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

33 --- map interface features

  1. Map is used to save data with mapping relationship: key value
  2. The Key and Value in the Map can be data of any reference type
  3. Duplicate keys in Map are not allowed for the same reason as HashSet
  4. The Value in the Map can be repeated
  5. The key and value in the Map can be null. Note that only one key can be null
  6. String class is often used as key in Map
  7. There is a one-way one-to-one correspondence between key and value, that is, the corresponding value can always be found by specifying key
  8. The k-v of the Map is stored in the Node

35 --- common methods of map

  1. put: add
  2. remove: deletes the mapping relationship according to the key
  3. Get: get the value according to the key
  4. size: get the number of elements
  5. isEmpty: judge whether it is empty
  6. Clear: clear
  7. containsKey: check whether the key exists

39 --- HashMap capacity expansion mechanism

  • The capacity expansion mechanism is the same as HashSet
    1. The underlying layer of HashMap maintains an array table of Node type, which is null by default
    2. When creating a HashMap object, initialize the load factor to 0.75
    3. When k-v is added, the key hash value is used to get the index in the table, and then judge whether there are elements in the index. If there are no elements, it is added directly; If yes, continue to judge whether the key of the element is equal to the key of the element to be added. If equal, replace the value. If not, judge whether it is a tree structure or a linked list structure and make corresponding processing. If it is found that the capacity is insufficient when adding, it needs to be expanded
    4. When adding elements for the first time, the capacity of the table needs to be expanded to 16, and the critical value is 12
    5. The capacity will be expanded later according to * * * 2x * * *
    6. In Java 8, if the number of elements in a linked list exceeds the default 8 and the size of the table is greater than or equal to the default 64, it will be trealized (red black tree)

42 --- basic introduction to hashtable

  1. The stored elements are key value pairs: k-v
  2. Neither key nor value can be null
  3. The use method is basically consistent with HashMap
  4. HashMap thread is not safe, HashTable thread is safe (synchronized is added)

43 --- hashtable expansion

  1. The bottom layer has an array Hashtable$Entry [], with an initialization size of 11
  2. Critical value: 11 * 0.75 = 8
  3. When it is greater than the critical value, the capacity shall be expanded by * * * 2 times + 1 * * *

Comparison between HashMap and HashTable:

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-w4rrxsla-1640566300157)( https://www.bilibili.com/video/BV1YA411T76k?p=43 )]

45 ---- how to select collection implementation classes in development

  1. First judge the storage type (a group of objects [single column] or a group of key value pairs [double column])
  2. A set of objects: Collection interface
    • Allow repetition: List (ordered and repeatable)
      • Add / delete: LinkedList [a two-way linked list is maintained at the bottom]
      • Change query: ArrayList [variable array of Object type is maintained at the bottom]
    • Do not repeat: Set (unordered and non repeatable)
      • Unordered: HashSet [the bottom layer is HashMap, which maintains the hash table, i.e. array + linked list + red black tree]
      • Sorting: TreeSet
      • The order of insertion and extraction is the same: LinkedHashSet [maintained array + bidirectional linked list]
  3. A set of key value pairs: Map
    • Key disorder: HashMap [the bottom layer is hash table (jdk1.7: array + linked list, jdk1.8: array + linked list + red black tree)]
    • Key sorting: TreeMap
    • The order of key insertion and extraction is the same: LinkedHashMap
    • Read file: Properties

46 --- introduction to TreeSet

  1. When using the parameterless constructor new TreeSet(), it is still unordered
  2. Using a constructor provided by TreeSet, you can pass in the comparator to make it orderly

47 --- introduction to treemap

It is basically the same as TreeSet, except that TreeMap stores the key value pair k-v

  1. When using the parameterless constructor new TreeSet(), it is still unordered
  2. Using a constructor provided by TreeSet, you can pass in the comparator to make it orderly

48----Collections tool class

  1. Collections is a tool class that operates on sets, lists, maps, etc
  2. Provides a series of methods
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

public class Collections_ {
    public static void main(String[] args) {

        ArrayList arrayList = new ArrayList();
        arrayList.add("Jack");
        arrayList.add("Tom");
        arrayList.add("Moon");
        arrayList.add("McGrady");
        System.out.println(arrayList);

        //reverse(List): flips the elements in it
        Collections.reverse(arrayList);
        System.out.println(arrayList);
        //shuffle(List): random sort
        Collections.shuffle(arrayList);
        System.out.println(arrayList);
        //sort(List): sort according to the natural order of elements
        Collections.sort(arrayList);
        System.out.println(arrayList);
        //sort(List,Comparator): sort them according to the specified comparator
        Collections.sort(arrayList, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((String)o1).length() - ((String)o2).length();
            }
        });
        System.out.println("Sort by string length:"+arrayList);
        //swap(List,int,int): swap elements at i and j
        Collections.swap(arrayList,0,3);
        System.out.println(arrayList);
        
        
        //Object max(Collection): returns the largest element in the collection by natural sorting of elements
        //Object max(Collection,Comparator):
        //Object min(Collection):
        //Object min(Collection,Comparator):
        //int frequency(Collection,Object): returns the number of occurrences of the specified element
        //void copy(List dest,List src): copy src contents into dest. Note that dest must be greater than or equal to the length of src
        //Boolean replaceall (list, object oldval, object newval): replace the old value in the list with the new value

    }
}

50 --- operation

Assignment 1:
import java.util.ArrayList;

@SuppressWarnings({"all"})
public class Homework01 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new News("More than 10 million new cases were confirmed, and millions of Hindu believers went to Ganges\"Holy bath\"Cause public concern"));
        arrayList.add(new News("The man suddenly remembered that the fish he caught two months ago was still in the net pocket. He picked it up and set it free"));

        int size = arrayList.size();
        //Reverse traversal
        for (int i = size - 1; i >= 0; i--) {
            //System.out.println(arrayList.get(i));
            News news = (News)arrayList.get(i);
            System.out.println(processTitle(news.getTitle()));
        }

    }
    //Write a method to deal with real news headlines
    public static String processTitle(String title) {

        if(title == null) {
            return "";
        }

        if(title.length() > 15) {
            return title.substring(0, 15) + "..."; //[0,15)
        } else {
            return title;
        }

    }
}

/**
 * Achieve as required:
 * (1) Encapsulate a news class, including title and content attributes, provide get and set methods, override toString method, and print only title when printing object;
 * (2) Only one constructor with parameters is provided. When instantiating an object, only the title is initialized; And instantiate two objects:
 * News 1: there are more than 10 million confirmed cases in Xinguan, and millions of Hindu believers go to the Ganges "holy bath" to arouse people's concern
 * News 2: the man suddenly remembered that the fish caught two months ago was still in the net pocket. He picked it up and set it free
 * (3) Add the news object to the ArrayList collection and traverse in reverse order;
 * (4) In the process of traversing the collection, the news headlines are processed. If they exceed 15 words, only the first 15 are retained, and then "..." is added after them
 * (5) Print and traverse the processed news headlines on the console;
 */
class News {
    private String title;
    private String content;

    public News(String title) {
        this.title = title;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public String toString() {
        return "News{" +
                "title='" + title + '\'' +
                '}';
    }
}

Assignment 2:
import java.util.ArrayList;
import java.util.Iterator;

@SuppressWarnings({"all"})
public class Homework02 {
    public static void main(String[] args) {

        ArrayList arrayList = new ArrayList();
        Car car = new Car("bmw", 400000);
        Car car2 = new Car("Bentley",5000000);
        //1.add: add a single element
        arrayList.add(car);
        arrayList.add(car2);
        System.out.println(arrayList);
        //* 2.remove: deletes the specified element
        arrayList.remove(car);
        System.out.println(arrayList);
        //* 3.contains: find whether the element exists
        System.out.println(arrayList.contains(car));//F
        //* 4.size: get the number of elements
        System.out.println(arrayList.size());//1
        //* 5.isEmpty: judge whether it is empty
        System.out.println(arrayList.isEmpty());//F
        //* 6.clear: clear
        //System.out.println(arrayList.clear(););
        //* 7.addAll: add multiple elements
        System.out.println(arrayList);
        arrayList.addAll(arrayList);//2 Bentleys
        System.out.println(arrayList);
        //* 8.containsAll: find whether multiple elements exist
        arrayList.containsAll(arrayList);//T
        //* 9.removeAll: deletes multiple elements
        //arrayList.removeAll(arrayList); // Equivalent to emptying
        //*To use the enhanced for and iterator to traverse all cars, you need to override the toString method of Car

        for (Object o : arrayList) {
            System.out.println(o);//
        }
        System.out.println("===iterator ===");
        Iterator iterator = arrayList.iterator();
        while (iterator.hasNext()) {
            Object next =  iterator.next();
            System.out.println(next);

        }

    }
}
/**
 * Use ArrayList to complete various operations on the object Car {name, price}
 * 1.add:Add a single element
 * 2.remove:Deletes the specified element
 * 3.contains:Find whether the element exists
 * 4.size:Get the number of elements
 * 5.isEmpty:Judge whether it is empty
 * 6.clear:empty
 * 7.addAll:Add multiple elements
 * 8.containsAll:Find whether multiple elements exist
 * 9.removeAll: Delete multiple elements
 * To use the enhanced for and iterator to traverse all cars, you need to override the toString method of Car
 */
class Car {
    private String name;
    private double price;

    public Car(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}

Operation 3:
import java.util.*;

@SuppressWarnings({"all"})
public class Homework03 {
    public static void main(String[] args) {

        Map m = new HashMap();
        m.put("jack", 650);//int->Integer
        m.put("tom", 1200);//int->Integer
        m.put("smith", 2900);//int->Integer
        System.out.println(m);

        m.put("jack", 2600);//Replace, update
        System.out.println(m);

        //Raise the salary of all employees by 100 yuan;
        //keySet
        Set keySet = m.keySet();
        for (Object key : keySet) {
            //to update
            m.put(key, (Integer)m.get(key) + 100);
        }
        System.out.println(m);

        System.out.println("=============ergodic=============");
        //Traverse EntrySet
        Set entrySet = m.entrySet();
        //iterator 
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry entry =  (Map.Entry)iterator.next();
            System.out.println(entry.getKey() + "-" + entry.getValue());

        }

        System.out.println("====Traverse all wages====");
        Collection values = m.values();
        for (Object value : values) {
            System.out.println("wages=" + value);
        }

    }
}
/**
 * Complete the following tasks as required
 * 1)Use the HashMap class to instantiate a Map type object m, and the key (String) and value (int) are used to store the employee's name and salary respectively,
 * The stored data are as follows: 	 jack - 650 yuan; tom - 1200 yuan; smith - 2900 yuan;
 * 2)Change jack's salary to 2600 yuan
 * 3)Raise the salary of all employees by 100 yuan;
 * 4)Traverse all employees in the collection
 * 5)Traverse all wages in the set
 */

Assignment 4: try to analyze how HashSet and TreeSet achieve de duplication respectively?
  1. The duplicate removal mechanism of HashSet: hashcode()+equals(), the bottom layer first obtains a hash value through the stored object operation, and obtains the corresponding index through the hash value. If it is found that there is no data at the location of the table index value, it will be stored directly; If there is data, use equals() to compare. If it is different after comparison, add it. Otherwise, do not add it.
  2. TreeSet's de duplication mechanism: if a Comparator anonymous object is passed in, the implemented compare() is used for de duplication. If the method returns 0, it is considered to be the same element and will not be added; If no Comparator anonymous object is passed in, the compareTo() method of the Comparable interface implemented by the added object will be used for de duplication.
import com.hspedu.map_.TreeMap_;

import java.util.TreeMap;
import java.util.TreeSet;

@SuppressWarnings({"all"})
public class Homework04 {
    public static void main(String[] args) {

        TreeSet treeSet = new TreeSet();
        treeSet.add("hsp");
        treeSet.add("tom");
        treeSet.add("king");
        treeSet.add("hsp");//Cannot be added because the compareTo() method of String compares the content
        System.out.println(treeSet);

    }
}

Assignment 5:
//import java.util.TreeSet;

//@SuppressWarnings({"all"})
//public class Homework05 {
//    public static void main(String[] args) {
//        TreeSet treeSet = new TreeSet();
//        //Analysis source code
//        //add method, because the TreeSet() constructor does not pass in the anonymous inner class of the Comparator interface
//        //So at the bottom, comparable <? super K> k = (Comparable<? super K>) key;
//        //That is, convert Perosn to Comparable type
//        treeSet.add(new Person());//ClassCastException.
//        treeSet.add(new Person());//ClassCastException.
//        treeSet.add(new Person());//ClassCastException.
//        treeSet.add(new Person());//ClassCastException.
//        treeSet.add(new Person());//ClassCastException.
//
//        System.out.println(treeSet);
//
//    }
//}
//
//class Person implements Comparable{
//
//    @Override
//    public int compareTo(Object o) {
//        return 0;
//    }
//}

Assignment 6:
import java.util.HashSet;
import java.util.Objects;

@SuppressWarnings({"all"})
public class Homework06 {
    public static void main(String[] args) {
        HashSet set = new HashSet();//ok
        Person p1 = new Person(1001,"AA");//ok
        Person p2 = new Person(1002,"BB");//ok
        set.add(p1);//ok
        set.add(p2);//ok
        p1.name = "CC";
        set.remove(p1);	//The index represented by the hash value of 1001, CC cannot be found, because AA - CC does not change the hash value of 1001, AA
        System.out.println(set);//2
        set.add(new Person(1001,"CC"));
        System.out.println(set);//3
        set.add(new Person(1001,"AA"));
        System.out.println(set);//4

    }
}

class Person {
    public String name;
    public int id;

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return id == person.id &&
                Objects.equals(name, person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id);
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", id=" + id +
                '}';
    }
}

//===========================Results=================================
/*[Person{name='BB', id=1002}, Person{name='CC', id=1001}]
[Person{name='BB', id=1002}, Person{name='CC', id=1001}, Person{name='CC', id=1001}]
[Person{name='BB', id=1002}, Person{name='CC', id=1001}, Person{name='CC', id=1001}, Person{name='AA', id=1001}]
*/


Topics: Java Back-end