Java collection learning notes

aggregate

      |----Collection Interface: a single column collection used to store objects one by one
          |----List Interface: store ordered and repeatable data.  -->"Dynamic array
              |----ArrayList,LinkedList,Vector

          |----Set Interface: stores unordered and unrepeatable data   -->"Collection" in high school
              |----HashSet,LinkedHashSet,TreeSet

      |----Map Interface: a two column set used to store a pair of data(key - value)A pair of data   -->High school function: y = f(x)
              |----HashMap,LinkedHashMap,TreeMap,Hashtable,Properties

Collection interface

  • common method
    add(Object e): add element e to the collection coll
    size(): get the number of added elements
    addAll(Collection coll1): adds the elements in the coll1 collection to the current collection
    clear(): clear collection elements
    isEmpty(): judge whether the current collection is empty
    contains(Object obj): determines whether the current collection contains obj
    containsAll(Collection coll1): judge whether all elements in the formal parameter coll1 exist in the current collection.
    remove(Object obj): removes the obj element from the current collection. If the element does not exist, false is returned.
    removeAll(Collection coll1): subtraction: removes all elements (including duplicates) in coll1 from the current collection.
    Retain all (collection coll1): intersection: get the intersection of the current collection and coll1 collection and return it to the current collection
    equals(Object obj): to return true, the elements of the current set and the parameter set must be the same. Inconsistent order is also false
    hashCode(): returns the hash value of the current object
    toArray(): Set - > array
    Static method Arrays.asList(): array - > collection
    When adding data obj to the object of the implementation class of the Collection interface, the class of obj is required to override equals()
public void test1(){
    Collection coll = new ArrayList();

    coll.add("AA");
    coll.add(123);//Automatic packing
    coll.add(456);//Automatic packing
    coll.add(new Date());
    coll.add(new String("Tom"));
    coll.add(false);
    /**************************/
    System.out.println(coll.size());//3
    /**************************/
    //When judging, we will call equals() of the class where the obj object is located.
    boolean contains = coll.contains(123);
    /**************************/
    Collection coll0 = Arrays.asList(123,4567);
    System.out.println(coll.containsAll(coll0));
    /**************************/
    coll.remove(123);
    System.out.println(coll);
    /**************************/
    Collection coll1 = new ArrayList();
    coll1.add(456);
    coll1.add("CC");
    coll.addAll(coll1);
    /**************************/
    Collection coll2 = Arrays.asList(123,456);
    coll.removeAll(coll2);
    System.out.println(coll);
    /**************************/
    Collection coll3 = Arrays.asList(123,456,789);
    coll.retainAll(coll3);
    System.out.println(coll);
    /**************************/
    Collection coll4 = new ArrayList();
    coll4.add("AA");
    coll4.add(456);//Automatic packing
    coll4.add(123);//Automatic packing
    coll4.add(new Date());
    coll4.add(new String("Tom"));
    coll4.add(false);
    System.out.println(coll.equals(coll4));    //
    /**************************/
    Object[] arr = coll.toArray();
    for(int i = 0;i < arr.length;i++){
        System.out.println(arr[i]);
    }
    /**************************/
    List<String> list = Arrays.asList("AA", "BB", "CC");
    System.out.println(list);
    /**************************/
    //clear(): clear collection elements
    coll.clear();
    /**************************/
    //isEmpty(): judge whether the current collection is empty
    System.out.println(coll.isEmpty());
}

List interface framework

|----Collection Interface: a single column collection used to store objects one by one
      |----List Interface: store ordered and repeatable data.  -->"Dynamic array,Replace the original array
          |----ArrayList: As List Main implementation classes of the interface; Unsafe thread and high efficiency; Bottom use Object[] elementData storage
          |----LinkedList: This kind of efficiency ratio is used for frequent insertion and deletion operations ArrayList High; The bottom layer uses two-way linked list storage
          |----Vector: As List Interface implementation class; Thread safety and low efficiency; Bottom use Object[] elementData storage
  • JDK8.0 ArrayList
    ArrayList list = new ArrayList();// The underlying Object[] elementData is initialized to {}. An array with a length of 10 is not created
    ist.add(123);// The first time add() is called, the underlying layer creates an array of length 10 and adds data 123 to elementData[0]
    ...
    list.add(11);// If the capacity of the underlying elementData array is insufficient due to this addition, the capacity will be expanded.
    By default, the capacity expansion is 1.5 times of the original capacity, and the data in the original array needs to be copied to the new array.
    Conclusion: it is recommended to use a constructor with parameters in development: ArrayList = new ArrayList (int capacity)

  • JDK8.0 LinkedList
    LinkedList list = new LinkedList(); The first and last attributes of Node type are declared internally, and the default value is null
    list.add(123);// Encapsulate 123 into Node and create Node object.

    Node is defined as a two-way linked list that embodies LinkedList

    private static class Node<E> {
        E item;
        Node<E> next;
        Node<E> prev;
    
        Node(Node<E> prev, E element, Node<E> next) {
        this.item = element;
        this.next = next;
        this.prev = prev;
        }
    }
    
  • common method
    void add(int index, Object ele): inserts an ele element at the index position
    boolean addAll(int index, Collection eles): add all elements in eles from the index position
    Object get(int index): gets the element at the specified index position
    int indexOf(Object obj): returns the position where obj first appears in the collection
    int lastIndexOf(Object obj): returns the last occurrence of obj in the current collection
    Object remove(int index): removes the element at the specified index position and returns this element
    Object set(int index, Object ele): sets the element at the specified index position to ele
    List subList(int fromIndex, int toIndex): returns a subset from fromIndex to toIndex
    Add: add(Object obj)
    Delete: remove(int index) / remove(Object obj)
    Change: set(int index, Object ele)
    Query: get(int index)
    Insert: add(int index, Object ele)
    Length: size()
    Traversal: ① Iterator iterator mode
    ② Enhanced for loop
    ③ Ordinary cycle

@Test
public void test1(){
    ArrayList list = new ArrayList();
    list.add(123);
    list.add(456);
    list.add("AA");
    list.add(new Person("Tom",12));
    list.add(456);

    System.out.println(list);

    //void add(int index, Object ele): inserts an ele element at the index position
    list.add(1,"BB");
    System.out.println(list);

    //boolean addAll(int index, Collection eles): add all elements in eles from the index position
    List list1 = Arrays.asList(1, 2, 3);
    list.addAll(list1);
//        list.add(list1);
    System.out.println(list.size());//9

    //Object get(int index): gets the element at the specified index position
    System.out.println(list.get(0));
}

@Test
public void test2(){
    ArrayList list = new ArrayList();
    list.add(123);
    list.add(456);
    list.add("AA");
    list.add(new Person("Tom",12));
    list.add(456);
    //int indexOf(Object obj): returns the position where obj first appears in the collection. If it does not exist, - 1
    int index = list.indexOf(4567);
    System.out.println(index);

    //int lastIndexOf(Object obj): returns the last occurrence of obj in the current collection. If it does not exist, - 1
    System.out.println(list.lastIndexOf(456));

    //Object remove(int index): removes the element at the specified index position and returns this element
    Object obj = list.remove(0);
    System.out.println(obj);
    System.out.println(list);

    //Object set(int index, Object ele): sets the element at the specified index position to ele
    list.set(1,"CC");
    System.out.println(list);

    //List subList(int fromIndex, int toIndex): returns a subset of the left closed right open interval from fromIndex to toIndex
    List subList = list.subList(2, 4);
    System.out.println(subList);
    System.out.println(list);
}

iterator

  • The traversal operation of collection elements uses the Iterator iterator interface
    1. Internal methods: hasNext() and next()
    2. Every time a collection object calls the iterator() method, it gets a new iterator object, and the default cursor is before the first element of the collection.
    3. Remove () is defined internally, which can delete the elements in the collection during traversal. This method is different from the direct call to remove() from a collection
      Note: the difference between java iterators and C + + is that C + + generally uses begin() to obtain the iterator pointing to the first element and traverse to the next iterator of the tail element. The initial iterator obtained by java is the previous iterator pointing to the first element and traverse to the last iterator pointing to the tail element.
@Test
public void test3(){
    Collection coll = new ArrayList();
    coll.add(123);
    coll.add(456);
    coll.add(new Person("Jerry",20));
    coll.add(new String("Tom"));
    coll.add(false);

    //Delete "Tom" in the collection
    Iterator iterator = coll.iterator();
    while (iterator.hasNext()){
//            iterator.remove();
        Object obj = iterator.next();
        if("Tom".equals(obj)){
            iterator.remove();
//                iterator.remove();
        }

    }
    //Traversal set
    iterator = coll.iterator();
    while (iterator.hasNext()){
        System.out.println(iterator.next());
    }
}

for loop traversal mode

    public void test3(){

        String[] arr = new String[]{"MM","MM","MM"};
        
        //Mode 2: enhanced for loop
        for(String s : arr){
            s = "GG";
        }

        for(int i = 0;i < arr.length;i++){
            System.out.println(arr[i]);
        }
    }

Set

 |----Collection Interface: a single column collection used to store objects one by one
          |----Set Interface: stores unordered and unrepeatable data   -->"Collection" in high school
              |----HashSet: As Set Main implementation classes of the interface; Thread unsafe; Can store null value
                  |----LinkedHashSet: As HashSet Subclasses of; When traversing its internal data, it can be traversed in the order of addition
                                      For frequent traversal operations, LinkedHashSet Higher efficiency HashSet.
              |----TreeSet: You can sort according to the specified attributes of the added object.

The class of data added to set (mainly HashSet and LinkedHashSet) must override hashCode() and equals()
Requirement: the rewritten hashCode() and equals() should be consistent as much as possible: equal objects must have equal hash codes.
Tip for rewriting two methods: the properties in the object used for the equals() method comparison should be used to calculate the hashCode value.

  • Set: stores unordered and non repeatable data. Take HashSet as an example:

    1. Disorder: not equal to randomness. The stored data is not added in the order of array index in the underlying array, but determined according to the hash value of the data.
    2. Non repeatability: ensure that when the added element is judged according to equals(), it cannot return true. That is, only one same element can be added.
  • Process of adding elements: take HashSet as an example:

    1. Add element a to the HashSet. First, call the hashCode() method of the class where element a is located to calculate the hash value of element a,
    2. This hash value then calculates the storage position (i.e. index position) in the underlying array of HashSet through some algorithm to judge
    3. Whether the array already has elements at this position:
      3.1 if there are no other elements in this position, element a is added successfully. > Case 1
      3.2 if there are other elements b (or multiple elements in the form of linked list) in this position, compare the hash values of element a and element b:
      3.3 if the hash values are different, element a is added successfully. - > case 2
      3.4 if the hash values are the same, you need to call the equals() method of the class where element a is located:
      equals() returns true, element a addition failed
      If equals() returns false, element a is added successfully. - > case 3
      For addition success case 3, element a and the data already existing at the specified index location are stored in a linked list.

HashSet bottom layer: array + linked list structure.

TreeSet

  1. The data added to TreeSet must be objects of the same class.
  2. There are two sorting methods: natural sorting (implementing Comparable interface) and custom sorting (Comparator)
  3. In natural sorting, the criteria for comparing whether two objects are the same is: compareTo() returns 0. It is no longer equal()
  4. In custom sorting, the criteria for comparing whether two objects are the same is: compare() returns 0. It is no longer equal()

Map

  |----Map:Dual column data, storage key-value Right data   ---Functions similar to high school: y = f(x)
         |----HashMap:As Map The main implementation class of; thread unsafe, high efficiency; storage null of key and value
              |----LinkedHashMap:Guaranteed in traversal map Elements can be traversed in the order they are added.
                      Reason: in the original HashMap Based on the underlying structure, a pair of pointers are added to point to the previous and subsequent elements.
                      For frequent traversal operations, this kind of execution efficiency is higher than HashMap. 
         |----TreeMap:Ensure that the added key-value Sort the and realize sorting traversal. At this time, consider key Natural sorting or custom sorting
                      Red and black trees are used at the bottom
         |----Hashtable:As an ancient implementation class; thread safe, inefficient; unable to store null of key and value
              |----Properties:Commonly used to process configuration files. key and value All String type

The bottom layer of HashMap: array + linked list + red black tree

Understanding of Map structure

Keys in Map: unordered and non repeatable. Use Set to store all keys - > the class where the key is located should override equals() and hashCode() (take HashMap as an example)
Value in Map: unordered and repeatable. Use Collection to store all values - > the class where value is located should override equals()
A key value pair: key value constitutes an Entry object.
Entries in Map: unordered and non repeatable. Use Set to store all entries

HashMap underlying implementation

1. HashMap map = new HashMap():
2. First call put()Method, the underlying layer creates a length of 16 Node[]array
3. First, call key1 Class hashCode()calculation key1 Hash value, which is calculated by some algorithm Entry The storage location in the array.
    1. If the data at this location is empty, the key1-value1 Added successfully. ----Case 1
    2. If the data at this location is not empty,(Means that one or more data exists at this location(Exist as a linked list)),compare key1 And the hash value of one or more existing data:   
        1. If key1 The hash value of is different from that of the existing data. At this time key1-value1 Added successfully.----Case 2
        2. If key1 The hash value of and a data that already exists(key2-value2)The hash value of is the same, continue to compare: call key1 Class equals(key2)Method, comparison:
                1. If equals()return false:here key1-value1 Added successfully.----Case 3
                2. If equals()return true:use value1 replace value2. 
4. In the process of continuous addition, capacity expansion will be involved when the critical value is exceeded(And the location to be stored is not empty)The default expansion method is to double the original capacity and copy the original data.
5. The number of data in the form of a linked list when the element at an index position of the array exists > 8 And the length of the current array > 64 At this time, the data at this index position is stored in red black tree instead.

Several constants in Map

DEFAULT_INITIAL_CAPACITY : HashMap Default capacity of, 16
DEFAULT_LOAD_FACTOR: HashMap Default load factor for: 0.75
threshold: Critical value of capacity expansion,=capacity*Fill factor: 16 * 0.75 => 12
TREEIFY_THRESHOLD: Bucket If the length of the linked list is greater than the default value, it will be converted into a red black tree:8
MIN_TREEIFY_CAPACITY: In the bucket Node Smallest when treelized hash Table capacity:64

Common methods of Map

Add, delete and modify:
Object put(Object key,Object value): adds (or modifies) the specified key value to the current map object
void putAll(Map m): store all key value pairs in m into the current map
Object remove(Object key): removes the key value pair of the specified key and returns value
void clear(): clear all data in the current map
Operation of element query:
Object get(Object key): get the value corresponding to the specified key
boolean containsKey(Object key): whether the specified key is included
boolean containsValue(Object value): whether the specified value is included
int size(): returns the number of key value pairs in the map
boolean isEmpty(): judge whether the current map is empty
boolean equals(Object obj): judge whether the current map and parameter object obj are equal
Method of metaview operation:
Set keySet(): returns the set set composed of all keys
Collection values(): returns the collection collection composed of all values
Set entrySet(): returns the set set composed of all key value pairs

Summary: common methods:
Add: put(Object key,Object value)
Delete: remove(Object key)
Modify: put(Object key,Object value)
Query: get(Object key)
Length: size()
Traversal: keySet() / values() / entrySet()

Like TreeSet, TreeSet also needs to implement the compareTo method or custom Comparator with the filled class

ProPerties

This class is generally used to read the configuration information of *. properties configuration files

public class PropertiesTest {

    //Properties: commonly used to handle configuration files. Both key and value are String types
    public static void main(String[] args)  {
        FileInputStream fis = null;
        try {
            Properties pros = new Properties();
            
            fis = new FileInputStream("test.properties");
            pros.load(fis);//Load the file corresponding to the stream

            String name = pros.getProperty("name");
            String password = pros.getProperty("password");

            System.out.println("name = " + name + ", password = " + password);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}
  • The configuration file test.properties is in the following form, with no space around =
name=111
password=abc

Tags: Java

Posted on Thu, 30 Sep 2021 17:58:41 -0400 by jkkenzie