Collection of Java foundations

Keywords: Java Database data structure

1. Overview of the collection

1.1 related concepts

  1. Sets and arrays are structures that store multiple data, referred to as java containers for short (Note: storage at this time mainly refers to memory storage and does not involve persistent storage, such as databases and txt files)
  2. Advantages of arrays in storing multiple data structures
  • Once initialized, the length is determined
  • Once the array is defined, its element type is determined. We can only operate on the data of the specified type
  1. Array has many disadvantages in data structure
  • Once initialized, its length cannot be modified
  • The methods provided in the array are very limited. It is very inconvenient and inefficient to add, delete and insert data
  • The requirement to obtain the actual number of elements in the array. There are no ready-made properties and methods available for the array
  • Array has the characteristics of data: orderly and repeatable. The disordered and unrepeatable requirements cannot be met

1.2 classification of Java collections

Java collections can be divided into Collection and Map systems

  1. Collection interface: single column data, which defines a set of data storage methods
  • List: an ordered and repeatable set of elements (LLinkedList, ArrayList, Vector)
  • Set: an unordered and non repeatable set of elements (HashSet, LinkHashSet, TreeSet)
  1. Map interface
  • Double column data, saving the "key value pair" set with mapping relationship (HashMap, LinkedHaspMap, TreeMap, HashTable, Properties)

2.Collection

2.1 interface method

  1. add to
    add(Object obj)
    addAll(Collection coll)
  2. Get the number of valid elements
    int size()
  3. Empty collection
    void clear()
  4. Is it an empty collection boolean isEmpty()
  5. Include an element
    boolean contains(Object obj): it is used to judge whether it is the same object through the equals method of the element
    boolean containsAll(Collection c): it also calls the equals method of the element for comparison. Compare the elements of two sets one by one.
  6. delete
    boolean remove(Object obj): judge whether it is the element to be deleted through the equals method of the element. Only the first element found is deleted
    boolean removeAll(Collection coll): take the difference set of the current set
  7. Take the intersection of two sets
    Boolean retain all (collection c): save the result of intersection in the current collection without affecting c
  8. Are sets equal
    boolean equals(Object obj)
  9. Convert to object array
    Object[] toArray()
  10. Gets the hash value of the collection object
    hashCode()
  11. ergodic
    iterator(): returns an iterator object for collection traversal
    give an example
    public static void main(String[] args) {
        Collection collection = new ArrayList();
        collection.add("11");//Add element
        collection.add("22");
        collection.add("33");
        System.out.println(collection.size());//Get the number of valid elements
        System.out.println(collection.isEmpty());//Is it empty
        System.out.println(collection.contains("11"));//Include an element
        collection.remove("11");//: judge whether it is the element to be deleted through the equals method of the element. Only the first element found is deleted
        System.out.println("==========================");
        for(Object o:collection)
        {
            System.out.println(o);
        }
        String s = collection.toString();
        System.out.println(s);
        Object[] objects = collection.toArray();//Convert to array
        System.out.println("==================================");
        for(Object o:objects)
        {
            System.out.println(o);
        }
        System.out.println("========================");
        ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add("22");
        collection.removeAll(objects1);//Difference set of the current set
        for(Object o:collection)
        {
            System.out.println(o);
        }
        collection.add("22");
        System.out.println("=====================");
        boolean b = collection.retainAll(objects1);//Gets the intersection of two sets
//        System.out.println(b);
        for(Object o:collection)
        {
            System.out.println(o);
        }
        System.out.println(collection.equals(objects1));//Judge whether two sets are equal
        
    }

3.Iterator iterator interface

3.1 traversing collection elements using the Iterator interface

  1. The Iterator object is called an Iterator (a kind of design pattern) and is mainly used to traverse the elements in the Collection.
  2. GOF defines the iterator pattern as providing a way to access each element in a container object without exposing the internal details of the object. The iterator pattern is born for containers. Similar to "conductor on the bus", "stewardess on the train" and "stewardess".
  3. The Collection interface inherits the java.lang.iteratable interface, which has an iterator() method, so all Collection classes that implement the Collection interface have an iterator() method to return an object that implements the Iterator interface.
  4. Iterator is only used to traverse collections, and iterator itself does not provide the ability to load objects. If you need to create an iterator object, you must have a collection that is iterated.
  5. 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.2 method of iterator interface

  1. Use next() to get the next element in the sequence.
  2. Use hasNext() to check whether there are any elements in the sequence.
  3. Use remove() to delete the newly returned element from the iterator.
 public static void main(String[] args) {
        ArrayList<Object> arrayList = new ArrayList<>();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        Iterator<Object> iterator = arrayList.iterator();
        //Traversal mode I
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println(iterator.next());
        System.out.println("================================");
        iterator= arrayList.iterator();
        //Traversal mode 2
        for(int i=0;i<arrayList.size();i++)
        {
            System.out.println(iterator.next());
        }

        iterator=arrayList.iterator();
        System.out.println("================================");
        //Traversal mode 3
        while (iterator.hasNext())//Determines whether there is a next element
        {
        //next(): ① move the pointer down ② return the elements at the collection position after moving down
            System.out.println(iterator.next());
        }
    }

Use of remove

   @Test
    public void tes1(){
       ArrayList<Object> arrayList = new ArrayList<>();
       arrayList.add(1);
       arrayList.add(2);
       arrayList.add(3);
       Iterator<Object> iterator = arrayList.iterator();
       while(iterator.hasNext())
       {
           int next = (int)iterator.next();
           if(next==1)
           {
               iterator.remove();
           }
       }
       iterator=arrayList.iterator();
       while(iterator.hasNext())
       {
           System.out.println(iterator.next());
       }
   }

be careful:

  • Iterator can delete the elements of the collection, but it is the remove method of the iterator object during traversal, not the remove method of the collection object.
  • If next() has not been called or the remove method has been called since the next method was called last time, then calling remove will report IllegalStateException.

3.3 traversing set elements using foreach loops

  1. Java 5.0 provides foreach loop iterations to access collections and arrays.
  2. The traversal operation does not need to get the length of the Collection or array, and does not need to use an index to access elements.
  3. Traverse the bottom layer of the collection and call Iterator to complete the operation.
  4. foreach can also be used to traverse arrays.
  5. Modifying the traversal result will not change the original value
//For (type local variable of collection element: collection object) still calls the iterator internally
   @Test
    public void text2()
   {
       ArrayList<Object> arrayList = new ArrayList<>();
       arrayList.add(1);
       arrayList.add(2);
       arrayList.add(3);
       for(Object x:arrayList)
       {
           System.out.println(x);
       }
   }

4.List interface

4.1 overview of list interface

  • Colocation interface: a single column collection is used to store objects
  • List interface: store ordered and repeatable data and dynamic array to replace the original array
  • list interfaces include ArrayList, LinkedList and vector

4.2 similarities and differences among ArrayList, LinkedList and vectors

Same: all three implement the List interface, and the characteristics of storing data are the same: storing orderly and repeatable data
Different:

  • ArrayList, as the main implementation class of List, has unsafe threads and high efficiency. The underlying layer uses Object[] elementData storage
  • LinkedList: corresponding to frequent insert and delete operations, the efficiency is higher than ArrayList, and the bottom layer uses two-way linked list storage
  • vector: as an ancient implementation class of the List interface, it is thread safe and inefficient. The underlying layer uses Object[] elementData storage

4.3 ArrayList source code analysis

  1. Below jdk7
    Create an Object[] elementData array with a length of 10 at the bottom layer and use add to add elements to the array. If adding elements leads to insufficient capacity of the underlying Object[] elementData array, the capacity will be expanded. By default, the capacity will be expanded to 1.5 times of the original data, and the original data will be assigned to the new array. It is recommended to use the constructor with parameters ArrayList LSIT = new ArrayList in development (int capacity)
  2. Changes of ArrrayList in jdk8
    The underlying Object[] elementData array is initialized to {} without creating a length. The first time add() is called, the underlying object creates an array with a length of 10 and adds the data to elementData. The subsequent adding and capacity expansion operations are the same as jdk7
    Summary: the creation of ArrayList object in jdk7 is similar to the starving mode of singleton mode, while the creation of ArrayList object in jdk8 is similar to the lazy mode of singleton mode, delaying the creation of array and saving memory

4.4LinkList

Use the form of linked list to store data

4.5 common methods of list interface

Method nameexplain
void add(int index, Object ele)Insert the 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 location
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 location and returns this element
Object set(int index, Object ele)Set the element at the specified index location to ele
List subList(int fromIndex, int toIndex)Returns a subset from fromIndex to toIndex
@Test
    public void test3()
   {
       ArrayList<Object> list = new ArrayList<>();
       list.add(1);//increase
       list.add(2);
       list.add(3);
       //difference
       for(int i=0;i<list.size();i++)
       {
           System.out.println(list.get(i));
       }
       list.remove(2);//Delete by subscript
       System.out.println("=====================");
       for(Object o:list)
       {
           System.out.println(o);
       }
       list.set(0,10);//change
       System.out.println("======================");
       for(Object o:list)
       {
           System.out.println(o);
       }
       list.remove(new Integer(10));//Delete by value
       System.out.println("=======================");
       for(Object o:list)
       {
           System.out.println(o);
       }
   }

LinkList new method
void addFirst(Object obj)
void addLast(Object obj)
Object getFirst()
Object getLast()
Object removeFirst()
Object removeLast()

4.6vector

When creating objects, the bottom layer creates an array with a length of 10. When expanding, it is expanded to twice the original

5 set interface

5.1 overview of set interface

  • set interface: stores unordered and non repeatable data
    Take Hashset as an example:
  1. Disorder: it is not equal to randomness. The stored data is not added in the order of the array index in the underlying array, but 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, the same element. Only one can be added
  • Hashset: as the main implementation class of the set interface, the thread is unsafe and can store null values
  • LinkedHashSet: as a subclass of HashSet, when traversing its internal data, it can be traversed in the order of addition
  • TreeSet: it can be sorted according to the added object attributes and stored in the way of red black tree
  1. HashSet sets the criteria for judging the equality of two elements: the two objects are equal through hashCode() method, and the return values of the equals() method of the two objects are also equal.
  2. For objects stored in the Set container, the corresponding classes must override the equals() and hashCode(Object obj) methods to implement the object equality rule. That is: "equal objects must have equal hash codes"

5.1.1 process of adding elements to HashSet

HashSet features

  1. HashSet is a typical implementation of the Set interface. This implementation class is used most of the time when using the Set set.
  2. HashSet stores the elements in the set according to the Hash algorithm, so it has good performance of access, search and deletion.
  3. HashSet has the following characteristics:
  • The order of elements cannot be guaranteed
  • HashSet is not thread safe
  • Collection elements can be null
  • 4.HashSet sets the criteria for judging the equality of two elements: the two objects are equal through hashCode() method, and the return values of the equals() method of the two objects are also equal. For objects stored in the Set container, the corresponding classes must override the equals() and hashCode(Object obj) methods to implement the object equality rule. That is: "equal objects must have equal hash codes".

When an element a is stored in the HashSet set, the HashSet will call the hashCode() method of the object to obtain the hashCode value of the object a, and then determine the storage position of the object in the underlying array of the HashSet through a hash function according to the hashCode value. (this hash function will calculate the subscript in the array with the length of the underlying array, and this hash function calculation also ensures that the elements can be stored evenly as much as possible. The more the hash distribution is, the better the hash function is designed.)
If the hashCode() values of two elements a and B are equal, the equals method will be called again. If the equals method results in true, the addition fails; If it is false, the element will be saved, but there are already elements in the position of the array, and the link will continue through a linked list.
If the hashcode() of two elements a and B are not equal, the addition is successful
jdk7: element a is placed in the array and points to the original element
jdk8: the original element is in the array, pointing to element a
Summary: 7 up and 8 down
Hashset bottom layer: array + linked list(
The initial capacity of the array is 16. If the utilization rate exceeds 0.75, the capacity will be doubled.
If the equals() method of two elements returns true, but their hashCode() return values are not equal, the hashSet will store them in different locations, but they can still be added successfully.

5.1.2 basic principles of rewriting hashCode() method

  • When the program runs, the same object calls the hashCode() method multiple times and should return the same value.
  • When the equals() method of two objects returns true, the return value of the hashCode() method of the two objects should also be equal.
  • The fields used for the equals() method comparison in the object should be used to calculate the hashCode value.

5.2 use of linkedhashset

LinkedHashSet is a subclass of HashSet. While adding data, each data also maintains two references to record the previous data and the next data of this data
Advantages: LinkedHashSet is more convenient for frequent traversal operations

   @Test
    public void test4()
   {
       HashSet<Object> hashSet = new LinkedHashSet<>();
       hashSet.add(1);
       hashSet.add(3);
       hashSet.add(1);
       hashSet.add("hollow word");
       hashSet.add("hi");
       for(Object o:hashSet)
       {
           System.out.println(o);
       }
   }

5.3TreeSet

  1. The data added to the TreeSet must be objects of the same class
  2. Two sorting methods: natural sorting and customized sorting (comparator)
  3. In natural sorting, the criterion for comparing whether two objects are equal returns 0 instead of equals for compareTo
    Natural sorting
public class People implements  Comparable{


    private String name;

    private int age;

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

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

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

    public People(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 int compareTo(Object o) {
        if(o instanceof People)
        {
            People o1 = (People) o;
            if(this.getAge()!=o1.getAge())
            {
                return this.getAge()<o1.getAge()?1:-1;
            }
            else
            {
                return this.getName().compareTo(o1.getName());
            }
        }
        return 0;
    }
}
   @Test
    public void test5(){
       TreeSet<People> treeSet = new TreeSet<>();
       treeSet.add(new People("zhangsan",19));
       treeSet.add(new People("zhangsan",90));
       treeSet.add(new People("lisi",23));
       treeSet.add(new People("wangqiang",44));
       treeSet.add(new People("aa",35));
       Iterator<People> iterator = treeSet.iterator();
       while (iterator.hasNext())
       {
           System.out.println(iterator.next());
       }
   }

Custom sorting

@Test
    public void text6()
   {
       Comparator comparator = new Comparator(){
           @Override
           public int compare(Object o1, Object o2) {
               if(o1 instanceof  People && o2 instanceof  People) {
                      People p1=(People) o1;
                   People p2=(People) o2;
                   if(p1.getAge()!=p2.getAge())
                   {
                       return p1.getAge()>p2.getAge()?1:-1;
                   }
                   else
                       return p1.getName().compareTo(p2.getName());
               }
               return 0;
           }
       };
       TreeSet treeSet = new TreeSet<>(comparator);
       treeSet.add(new People("zhangsan",19));
       treeSet.add(new People("zhangsan",90));
       treeSet.add(new People("lisi",23));
       treeSet.add(new People("wangqiang",44));
       treeSet.add(new People("aa",35));
       Iterator iterator = treeSet.iterator();
       while (iterator.hasNext())
       {
           System.out.println(iterator.next());
       }
   }

Classic examples

public class Person {
    private int id;
    private String name;

    @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(id, name);
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Person() {
    }

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


   @Test
    public void test7()
   {
       HashSet set = new HashSet();
       Person p1 = new Person(1001,"AA");
       Person p2 = new Person(1002,"BB");
       set.add(p1);
       set.add(p2);
       System.out.println(set);
       p1.setName("CC");
       set.remove(p1);
       System.out.println(set);
       System.out.println("=================");
       set.add(new Person(1001,"CC"));
       System.out.println(set);
       System.out.println("================");
       set.add(new Person(1001,"AA"));
       System.out.println(set);
   }

6. Map interface

6.1Map Interface Overview

  1. Map and Collection exist side by side. 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. The key in the Map is stored in a Set and cannot be repeated. That is, the class corresponding to the same Map object must override the hashCode() and equals() methods
  4. String class is often used as the "key" of Map
  5. There is a one-way one-to-one relationship between key and value, that is, a unique and definite value can always be found through the specified key
  6. Common implementation classes of Map interface: HashMap, TreeMap, LinkedHashMap and Properties. Among them, HashMap is the most frequently used implementation class of Map interface

6.1 Map implementation class structure

  1. Map: double column data, which stores the data of key value pairs, similar to high school functions
  2. HashMap: as the main implementation class of Map, the thread is unsafe and efficient. It can store null key s and value s
  • LinkedHashMap: ensure that when traversing map elements, it can be implemented in the order of addition (add a pair of pointers to point to the previous and subsequent elements on the basis of the underlying results of the HashMap for reasons. For frequent traversal operations, this execution efficiency is higher than that of HashMap)
  1. TreeMap: make sure to sort according to the added key value; to realize sorting traversal. At this time, consider the natural sorting or customized sorting of keys, and the red black tree is used at the bottom
  2. HashTable: as an ancient implementation class, it is thread safe and inefficient. It cannot store null key s and value s
  • properties: commonly used to handle configuration files. Both key and value are Sting types

Bottom layer of HashMap:

  • jdk7 and before: array + linked list
  • jdk8 array + linked list + red black tree

Interview questions:
Underlying implementation principle of HashMap
Differences between HashMap and HashTable

6.2Map structure understanding

  • Keys in Map: unordered and non repeatable. Use set to store all keys (the class where the key is located should override the equals and hashCode methods)
  • 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

6.3 underlying implementation principle of has and Map, taking jdk7 as an example

The internal storage structure of HashMap is actually a combination of array and linked list.
HashMap<Object, Object> map = new HashMap<>(); After instantiation, the bottom layer creates an Entry[] table array with a length of 16 and adds entry1(key, value) to the HashMap. First, calculate the hash value of the key in entry1 (calculated according to the hashCode() of the class where the key belongs). After processing this hash value, get the location i to be stored in the bottom entry [] array. If there is no element at position i, entry1 is added successfully. If Entry2 already exists at position i (or entry3 and entry4 exist in the linked list), you need to compare the key in entry1 with other entries in turn through a circular method. If the hash values are different from each other, they will be added directly (and the original data will be stored in the form of linked list). If the hash values are different, continue to compare whether they are equal. If the return value is true, use the value of entry1 to replace the value of the entry whose equals is true. If all equals returns false after traversal, entry1 can still be added successfully (and the original data is stored in the form of a linked list). Entry1 points to the original entry element.
Capacity expansion will be involved in the process of continuous addition. When the critical value is exceeded (and the location to be stored is not empty), the capacity will be expanded to twice the original by default, and then the position of each element in the array will be recalculated
jdk8 is different from jdk7 in its underlying implementation

  1. The bottom layer of new HashMap() does not create an array with a length of 16
  2. jdk 8 geomagnetic field array is Node [] instead of Entry []
  3. The first time the put method is called, the underlying layer creates an array with a length of 16
  4. The bottom layer of jdk7 is only array + linked list, while the bottom layer of jdk8 is array + linked list + red black tree (when the number of elements in a certain position of the array in the form of linked list is 8 and the number of current arrays is greater than 64, all data in the index position will be stored in red black tree)

Important constants in HashMap source code

  • DEFAULT_ INITIAL_ Capability: default capacity of HashMap, 16
  • MAXIMUM_ Capability: maximum supported capacity of HashMap, 2 ^ 30
  • DEFAULT_LOAD_FACTOR: the default load factor of HashMap is 0.75
  • THRESHOLD: expansion critical value = capacity + expansion factor 16 * 0.75 > = 12
  • TREEIFY_THRESHOLD: if the length of the linked list in the Bucket is greater than the default value, it will be converted into a red black tree
  • UNTREEIFY_THRESHOLD: if the Node stored in the red black tree in the Bucket is less than the default value, it is converted into a linked list
  • MIN_ TREEIFY_ Capability: the minimum hash table capacity when the nodes in the bucket are trealized.

6.4 underlying principle of linkhashmap

  • LinkedHashMap is a subclass of HashMap
  • Based on the HashMap storage structure, a pair of two-way linked lists are used to record the order of adding elements
  • Similar to LinkedHashSet, LinkedHashMap can maintain the iteration order of Map: the iteration order is consistent with the insertion order of key value pairs

6.5Map common methods

  1. 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
  1. 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
  1. 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
    Common methods: add, modify, delete, query, length
   @Test
    public void text8()
   {
       HashMap<Object, Object> hashMap = new HashMap<>();
       //add to
       hashMap.put("a",1);
       hashMap.put("b",2);
       hashMap.put("c",4);
       System.out.println(hashMap);
       //modify
       hashMap.put("a",11);
       System.out.println(hashMap);
       //delete
       Object a = hashMap.remove("a");
       System.out.println(a);
       Object d = hashMap.remove("d");
       //Deleted data does not exist
       System.out.println(d);
       System.out.println(hashMap);
       //map size
       System.out.println(hashMap.size());
       //Is it empty
       System.out.println(hashMap.isEmpty());
       //Whether to include the specified key
       System.out.println(hashMap.containsKey("b"));
       //Whether to include the specified value
       System.out.println(hashMap.containsValue(2));
       //Returns the set set of the desired key
       Set<Object> keySet = hashMap.keySet();
       System.out.println("be-all key");
       for(Object k:keySet)
       {
           System.out.println(k);
       }
       System.out.println("be-all value");
       //Return the vaule you want
       Collection<Object> values = hashMap.values();
       for(Object o:values)
       {
           System.out.println(o);
       }
       System.out.println("key-value");
       //Get all key values
       //Mode 1
       Set<Map.Entry<Object, Object>> entries = hashMap.entrySet();
       Iterator<Map.Entry<Object, Object>> iterator = entries.iterator();
       while(iterator.hasNext())
       {
           Map.Entry<Object, Object> next = iterator.next();
           System.out.println(next.getKey()+"----->"+next.getValue());
       }
       //Mode II
       for(Object o:keySet)
       {
           System.out.println(o+"-------------->>>"+hashMap.get(o));
       }
   }

6.6 treemap sorting

Natural sorting
person.java

package com.blb.com;

import java.util.Objects;

/**
 * @author smilecb
 * @date 2021/9/12 0012 11:22
 */
public class Person implements Comparable{
    private int id;
    private String name;

    @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(id, name);
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Person() {
    }

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

    @Override
    public int compareTo(Object o) {
        if(o instanceof  Person)
        {
            Person p=(Person) o;
            if(this.getId()!=p.getId())
            {
                return this.getId()<p.id?1:-1;
            }
            else
            {
                return this.getName().compareTo(p.getName());
            }
        }
        return 0;
    }
}

Test class

   @Test
    public void text9()
   {
       TreeMap treeMap = new TreeMap<>();
       treeMap.put(new Person(1,"shangsan"),70);
       treeMap.put(new Person(3,"lisi"),60);
       treeMap.put(new Person(1,"wangwu"),80);
       treeMap.put(new Person(2,"cb"),66);
       Set set = treeMap.keySet();
       Iterator iterator = set.iterator();
       while (iterator.hasNext())
       {
           Object next = iterator.next();
           System.out.println(next+"---->"+treeMap.get(next));
       }
   }

Custom sorting

@Test
   public void text10()
   {
       Comparator<Object> objectComparator = new Comparator(

       ) {
           @Override
           public int compare(Object o1, Object o2) {
               if(o1 instanceof Person && o2 instanceof Person)
               {
                   Person p1=(Person) o1;
                   Person p2=(Person) o2;
                   if(!p1.getName().equals(p2.getName()))
                   return p1.getName().compareTo(p2.getName());
                   else
                       return p1.getId()-p2.getId();
               }
               return 0;
           }

       };
       TreeMap treeMap = new TreeMap<>(objectComparator);
       treeMap.put(new Person(1,"shangsan"),70);
       treeMap.put(new Person(3,"lisi"),60);
       treeMap.put(new Person(1,"wangwu"),80);
       treeMap.put(new Person(2,"lisi"),66);
       Set set = treeMap.keySet();
       Iterator iterator = set.iterator();
       while (iterator.hasNext())
       {
           Object next = iterator.next();
           System.out.println(next+"---->"+treeMap.get(next));
       }
   }

6.7 differences between HashMap and HashTable

  1. Hashtable is an ancient Map implementation class, which is provided by JDK1.0. Unlike HashMap, hashtable is thread safe.
  2. The implementation principle and function of Hashtable are the same as that of HashMap. The bottom layer uses hash table structure, which has fast query speed and can be used with each other in many cases.
  3. Unlike HashMap, Hashtable does not allow null as key and value
  4. Like HashMap, Hashtable cannot guarantee the order of key value pairs
  5. Hashtable judges that two key s are equal and two value s are equal, which is consistent with HashMap.

6.8Properties

  • The Properties class is a subclass of Hashtable, which is used to process property files
  • Since the key and value in the Properties file are of string type, the key and value in Properties are of string type
  • When accessing data, it is recommended to use setProperty(String key,String value) method and getProperty(String key) method

7. Collections tool class

  • Collections is a tool class that operates on collections such as Set, List, and Map
  • Collections provides a series of static methods to sort, query and modify collection elements. It also provides methods to set immutable collection objects and realize synchronous control over collection objects

7.1 differences between Collections and Collections

Collection is an interface, and Collections is a tool class for manipulating collection and Map

7.2 common methods

Method namedescribe
reverse(List)Reverse the order of elements in the List
shuffle(List)Random sorting of List collection elements
sort(List)Sorts the specified List collection elements in ascending order according to the natural order of the elements
sort(List,Comparator)Sorts the List collection elements according to the order generated by the specified Comparator
swap(List,int, int)Exchange the elements at i and j in the specified list collection
Object max(Collection)Returns the largest element in a given set according to the natural order of the elements
Object max(Collection,Comparator)Returns the largest element in a given collection in the order specified by the Comparator
Object min(Collection)Returns the smallest element in a given set according to the natural order of the elements
Object min(Collection,Comparator)Returns the smallest element in a given collection in the order specified by the Comparator
int frequency(Collection,Object)Returns the number of occurrences of the specified element in the specified collection
void copy(List dest,List src)Copy the contents of src to dest  Boolean replaceall (List, Object oldVal, Object newVal): replace all the old values of the List object with the new values

The Collections class provides multiple synchronizedXxx() methods, which can wrap the specified collection into a thread synchronized collection, so as to solve the thread safety problem when multiple threads access the collection concurrently

Posted by taurus5_6 on Mon, 13 Sep 2021 11:51:30 -0700