Java basics notes summary

Keywords: Java Back-end

1. Overview of arrays and sets

Collections and arrays are structures that store multiple data, referred to as Java containers for short.

Note: the storage at this time mainly refers to the storage at the memory level, and does not involve persistent storage (. TXT,. JPG,. Avi, in the database).

Characteristics of array storage:

  • Once initialized, its length is determined.
  • Once defined, the type of its element is determined. We can only operate on the specified type of data.
    For example: String [] arr, int [] Arr1, object [] arr2.

Disadvantages of array:

Advantages of collective storage:

  • Solve the disadvantages of array data storage.

2. Collection interface and Map interface collection

The Collection interface is a singleton Collection used to store objects one by one.
It has two sub interfaces: List interface and Set interface.

Collection interface inheritance tree:

The Map interface is a two column set used to store a pair of key - value data.

The following is the inheritance tree of the Map interface:

3. Collection interface collection

3.1 Collection interface method

package com.holmes.java07;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

public class CollectionTest2 {
    @Test
    public void test(){
        Collection coll = new ArrayList();

        //1. add(Object e): add element e to the collection coll
        coll.add("AA");
        coll.add("BB");
        coll.add(123);
        coll.add(new Date());

        //2. size(): get the number of added elements
        System.out.println(coll.size());

        //addAll(Collection collName): add all the elements in the collName collection to the current collection.
        Collection coll1 = new ArrayList();
        coll1.add(456);
        coll1.add("CC");
        coll.addAll(coll1);
        System.out.println(coll);

        //3. isEmpty(): judge whether the current collection is empty (not null, but whether there are elements in the collection)
        System.out.println(coll.isEmpty());//false

        Collection coll2 = new ArrayList();
        coll2.add(null);
        System.out.println(coll2.isEmpty());//false

        //4. clear(): clear set elements
        coll.clear();
        System.out.println(coll.isEmpty());

    }
}


matters needing attention:

  • The add() method can only fill in objects.
  • When adding data obj to the object of the implementation class of the Collection interface, the class where obj is located is required to override the equals() method (otherwise, when comparing with contain(), the address is compared instead of the value).
package com.holmes.java07;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

public class CollectionTest {
    @Test
    public void test1(){

        Collection coll = new ArrayList();

        //123 here is an object
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(false);

        coll.add(new Person("hello",22));
        Person p = new Person("Jerry",20);
        coll.add(p);

        //1. contains(Object obj): judge whether the current set contains obj
        boolean contains = coll.contains(123);
        System.out.println(contains);//true

        //Of course, the contain() method does not compare addresses. For example, if two strings with different addresses and the same content are created, the result returns true.
        //The reason is that the equals method is overridden in the String class, which is to compare the content, so true is returned here
        //In addition, equals comparison is carried out from beginning to end. The number of comparisons depends on where the position is.
        System.out.println(coll.contains(new String("Tom")));//true

        //For a class defined by yourself, if you do not override the equals method, you will call the method of the parent class Object by default, which is judged by = = instead of equals, and the address will be compared.
        System.out.println(coll.contains(new Person("hello",22)));//false
        System.out.println(coll.contains(p));//true

        //2. containsAll(Collection coll1): judge whether all elements in formal parameter coll1 exist in the current collection.

        //Arrays.asList is used to convert arrays into lists.
        Collection coll1 = Arrays.asList(123,456);
        System.out.println(coll.containsAll(coll1));


    }
}

class Person{
    private String name;
    private int age;

    public Person() {
    }

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package com.holmes.java07;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

public class CollectionTest {

    @Test
    public void test2(){

        //3. remove(Object obj): removes obj elements from the current collection.
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(new Person("hello",22));
        coll.add(false);

        coll.remove(123);
        System.out.println(coll);

        //4. removeAll(Collection collName): removes all elements in collName from the current collection
        //Remove the intersection between the two sides.
        Collection coll1 = Arrays.asList(456, new String("Tom"));
        coll.removeAll(coll1);
        System.out.println(coll);


    }

    @Test
    public void test3(){
        Collection coll = new ArrayList();
        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(new Person("hello",22));
        coll.add(false);

        Collection coll1 = Arrays.asList(123,456,789);

        //5. coll. Retain all (collName): take the intersection of coll and collName, and return the intersection to the current set (coll)
        coll.retainAll(coll1);
        System.out.println(coll);

        //6. equals(Object obj):
        Collection coll2 = new ArrayList();
        coll2.add(new String("Tom"));
        coll2.add(123);

        Collection coll3 = new ArrayList();
        coll3.add(new String("Tom"));
        coll3.add(123);

        System.out.println(coll2.equals(coll1));

        //It should be noted that the equals() method is the rewritten comparison value for types such as String. If equals of Object type is used, it is the comparison address.
        //This comparison requires another judgment
        System.out.println(coll3.equals(coll2));
    }
}

3.2 some methods of converting set to array and array to set

Set to array, array to set, etc.:

package com.holmes.java07;

import org.junit.Test;

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

public class CollectionTest3 {

    @Test
    public void test(){

        Collection coll = new ArrayList();

        coll.add(123);
        coll.add(456);
        coll.add(new String("Tom"));
        coll.add(new Person("hello",22));
        coll.add(false);

        //7. hashCode(): returns the hash value of the current object.
        System.out.println(coll.hashCode());

        //8. Set = array toArray():
        Object[] arr = coll.toArray();
        for (int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }

        //9. Array collection Arrays.asList() calls the static method asList() of Arrays class:
        List<String> list = Arrays.asList(new String[]{"AA", "BB", "CC"});
        System.out.println(list);//[AA, BB, CC]

        //int will treat 123456 as a whole as an element
        List ints = Arrays.asList(new int[]{123, 456});
        System.out.println(ints);
        System.out.println(ints.size());//1
        //The Integer wrapper class cannot be written
        List ints2 = Arrays.asList(new Integer[]{123, 456});
        System.out.println(ints2.size());


        //Another is to pass in two objects, that is, two elements. You can't confuse them!
        List ints4 = Arrays.asList(new String[]{"abc","efg"},new String[]{"hig","kml"});
        System.out.println(ints4);
        System.out.println(ints4.size());

        List ints3 = Arrays.asList(123,456);
        System.out.println(ints3);


        //9. iterator(): returns an instance of the iterator interface for traversing collection elements.
        System.out.println(coll.iterator());
    }

}

4. Iterator traversal

4.1 traversing the Collection using Iterator

The Collection interface inherits the java.lang.iteratable interface, which has an iterator() method, which naturally implements the combination of the Collection interface. Both have an iterator() method to return an object that implements the Iterator interface.

The Iterator interface has three methods:

  • hasNext() method: this method is used to determine whether there is another element.
  • next() method: move the pointer down and return the elements at the collection position after moving down.
  • iterator.remove() method: This is the remove method of the iterator. It can also delete elements in the collection, but it is different from the remove method of the collection. Be careful.

The collection traversal is generally as follows:

package com.holmes.java07;

import org.junit.Test;

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

public class Testset {
    @Test
    public void test(){

        Collection col = new ArrayList();
        col.add(123);
        col.add(456);
        col.add(new String("picturesque landscape"));
        col.add(false);

        //Use iterator to traverse the contents of the collection:
        Iterator iterator = col.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        //remove() method of iterator:
        Iterator iterator1= col.iterator();
        while (iterator1.hasNext()){

            Object obj = iterator1.next();

            if ("picturesque landscape".equals(obj)){
                //iterator.remove() method: you can also remove elements from the collection
                iterator1.remove();
            }

        }

        System.out.println(col);

    }

}

Two wrong uses of iterator remove:

  • You can't use remove at the beginning, otherwise the start pointer hasn't pointed to the first collection element, and you can't determine who to remove?
  • Moreover, if you call remove once, you can't call the second time, because if you call remove once, the current remove will be removed directly, and if you call again, the pointer still points to the removed position, an error will be reported naturally.
package com.holmes.java07;

import org.junit.Test;

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

public class Testset {
    @Test
    public void test(){

        Collection col = new ArrayList();
        col.add(123);
        col.add(456);
        col.add(new String("picturesque landscape"));
        col.add(false);


        Iterator iterator= col.iterator();

		//The first case:
        //report errors! java.lang.IllegalStateException
        //while (iterator.hasNext()){
        //    iterator.remove();
        //    System.out.println(iterator.next());
        //}

		//The second case:
        while (iterator.hasNext()){
            iterator.remove();
            System.out.println(iterator.next());
            iterator.remove();//This is also wrong!! report errors! java.lang.IllegalStateException
        }


    }

}

Iterator implementation principle:

4.2 traversing set elements using foreach loops

Traverse the collection through for:

You can also traverse the array:

5. list interface, one of the collection sub interfaces

5.1 specific classes of list interface

Under the list interface and the class definition, the elements are stored orderly and repeatable.

There are three classes under the list interface:

  • ArrayList class: as the main implementation class of the List interface; Threads are unsafe and efficient. The underlying layer uses Object[] elementData storage.
  • LinkedList class: the bottom layer uses two-way linked list storage. For frequent insertion and deletion operations, the efficiency of using this class is higher than that of ArrayList.
  • Vector class: as an ancient implementation class of the List interface; Thread safe and inefficient. The underlying layer uses Object[] elementData storage.

5.2 principle analysis of ArrayList class

ArrayList class: as the main implementation class of the List interface; Threads are unsafe and efficient. The underlying layer uses Object[] elementData storage.

ArrayList source code analysis:

jdk 7:

jdk 8:

5.3 principle analysis of LinkedList class

LinkedList class: the bottom layer uses two-way linked list storage. For frequent insertion and deletion operations, the efficiency of using this class is higher than that of ArrayList.

Because of the two-way chain, modification and insertion are more flexible.

5.4 Vector principle analysis

Vector class: as an ancient implementation class of the List interface; Thread safe and inefficient. The underlying layer uses Object[] elementData storage.

5.5 common methods of list interface

package com.holmes.java07;

import org.junit.Test;

import java.util.*;

public class Testset {
    @Test
    public void test(){

        ArrayList list = new ArrayList();
        list.add(123);
        list.add(456);
        list.add(new String("picturesque landscape"));
        list.add(false);

        //List. Add (int index, object element): insert element at the index position
        list.add(1,"AAA");
        System.out.println(list);

        //List. Addall (int index, collection elements): add all elements in elements to the collection from the index position
        List list2 = Arrays.asList(1,2,3,4);
        list.addAll(3,list2);
        System.out.println(list);

        //list.indexOf(Object obj): query the position of obj in the collection and return the index.
        int index = list.indexOf(456);
        System.out.println(index);

        //list.lastIndexOf(Object obj): returns the last occurrence of obj in the current collection.
        list.add(0,"picturesque landscape");
        int index2 = list.lastIndexOf("picturesque landscape");
        System.out.println(index2);

        //list.remove(int index) method: remove the element at the specified index position and return this element.
        Object obj = list.remove(2);
        System.out.println(obj);
        System.out.println(list);

        //List. Set (int index, object element) method: set the element at the specified index position as element.
        list.set(0,"Romance of the Three Kingdoms");
        System.out.println(list);

        //List. Sublist (int fromIndex, int toIndex): returns the subset from fromIndex to toIndex.
        List list1 = list.subList(1, 3);
        System.out.println(list1);
        
        //list.size(): returns the current collection length
        System.out.println(list.size());

        //list.get(Int index): returns the element at the current index position
        System.out.println(list.get(0));
    }

}

6. The second of the collection sub interfaces is the set interface

6.1 introduction to set interface

The set interface is a sub interface of Colection. It is not allowed to contain the same elements, and it is unordered.

Implementation class of Set interface:

  • HashSet: as the main implementation class of Set interface; Thread unsafe, null value can be stored.
    LinkedHashSet: as a subclass of HashSet; When traversing its internal data, it can be traversed in the order of addition.
  • TreeSet: you can sort according to the specified attributes of the added object.

There are no new methods defined in the Set interface, but all the methods declared in the Collection are used.

Disorder of Set interface:

  • Disorder is not equal to randomness. The order of stored data is not determined by index addition at the bottom, but by the hash value of the data.

Non repeatability of Set interface:

  • Ensure that when the added element is judged according to equals(), it cannot return true. That is, only one element can be added to the same element.

The principle of adding elements with the add() method is as follows: (important)

First, check whether the storage locations are the same. If they are different, add them directly; If the position is the same, compare the same hash value with different hash values, and add if the hash values are different; If the hash value is the same, compare equals and add if you want to be the same.

Set implements the capacity expansion method of HashSet class:

6.2 rewrite hashCode() and equals() methods in set

Detailed function of hashCode() method:

For the object in the Set container, the corresponding class must override the equals() and hashCode(Object obj) methods to implement the object equality rule. That is, "equal objects must have equal hash codes".

In normal times, the class we create should override the equals() and hashCode() methods directly through the system:

class Person01 {
    private String name;
    private int age;

    public Person01(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

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

6.3 HashSet and linkedhashset (subclasses of HashSet)

HashSet: as the main implementation class of Set interface; Thread unsafe, null value can be stored.

LinkedHashSet: as a subclass of HashSet, each data also maintains two references to record the previous data and the latter data of this data.

Advantages: LinkedHashSet is more efficient than HashSet for frequent traversal operations.

package com.holmes.java07;

import org.junit.Test;

import java.util.*;

public class SetTest {

    @Test
    public void test(){

        Set set = new HashSet();
        set.add(456);
        set.add(123);
        set.add("AA");
        set.add("CC");
        System.out.println(set);

        Set set2 = new LinkedHashSet();
        set2.add(456);
        set2.add(123);
        set2.add("AA");
        set2.add("CC");
        System.out.println(set2);

    }

}

6.4 natural sorting and customized sorting of TreeSet

First, TreeSet cannot add objects of different classes! Otherwise, an error java.lang.ClassCastException will be reported. Only properties of the same class can be added.

TreeSet traversal should cooperate with rewriting the toString method, or the returned address value.

6.4.1 TreeSet natural sorting

Natural sorting requires that the class in TreeSet implement the comparable interface and override the compareTo method and toString() method.

package com.holmes.java07;

import org.junit.Test;

import java.util.*;

public class SetTest {

    @Test
    public void test(){

        TreeSet set = new TreeSet();
        set.add(new User("Tom",22));
        set.add(new User("Aerry",24));
        set.add(new User("Mim",49));
        set.add(new User("Mim",36));
        set.add(new User("Jack",12));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

    }

}

class User implements Comparable{

    private String name;
    private int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }


    @Override
    public int compareTo(Object o) {
        //Sort by name from small to large
        if (o instanceof User){

            User user = (User)o;
            int compare = this.name.compareTo(user.name);

            //If the names are the same size, compare the age
            if (compare != 0){
                return compare;
            }else {
            	//Here is the compare method of Integer, remember!!
                return Integer.compare(this.age,user.age);
            }

        }else {
            throw new RuntimeException("The types entered do not match");
        }
    }

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

6.4.2 customized sorting of TreeSet

Custom sorting is to define comparator as a parameter and pass it to TreeSet.

package com.holmes.java07;

import org.junit.Test;

import java.util.*;

public class SetTest {


    @Test
    public void test2(){
        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                //Sort by age:
                if (o1 instanceof User && o2 instanceof User){
                    User u1 = (User) o1;
                    User u2 = (User) o2;
                    return Integer.compare(u1.getAge(),u2.getAge());
                }else {
                    throw new RuntimeException("The data types entered do not match");
                }
            }
        };

        TreeSet set = new TreeSet(comparator);

        set.add(new User("Tom",22));
        set.add(new User("Aerry",24));
        set.add(new User("Mim",49));
        set.add(new User("Mim",36));
        set.add(new User("Jack",12));

        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }


}

class User {

    private String name;
    private int age;

    public User(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 String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

7. Map interface

7.1 Map interface implementation class and structure principle

Map interface: double column data, which stores the data of key value pairs, similar to the correspondence between y and x in mathematics.

Map interface implementation class:

  • HashMap: as the main implementation class of Map; Unsafe thread and high efficiency; Can store null key and value.

    LinkedHashMap: it is a subclass of HashMap. Based on the original HashMap 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.

  • Hashtable: (note the lowercase t here) as an ancient implementation class; Thread safety and low efficiency; Cannot store null key and value.

    Properties: commonly used to process configuration files. Both key and value are String types. (for example, the properties file of jdbc).

  • TreeMap: ensure to sort according to the added key value pairs and realize sorting traversal. At this time, the natural sorting or customized sorting of keys should be considered.

Structure principle of Map:

  • Keys in Map: unordered and non repeatable. Use Set to store all key s.
  • Values in Map: unordered and repeatable. Use Collection to store all value s.
  • A key value pair: key value constitutes an entry object. Entries in Map: unordered and non repeatable. Set is used to store all entries.

7.2 underlying implementation principle of HashMap?

JDK 7:


Since the problem of capacity expansion involves arrays, there must be capacity expansion. The default capacity expansion method of HashMap is to double the original capacity and copy the original data.

JDK 8:

The underlying implementation principle of LinkedHashMap?

7.3 some common methods of map interface

Basic operation methods of Map:

package com.holmes.java07;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;


public class MapTest {

    @Test
    public void test(){

        Map map = new HashMap();

        //Map. Put (object key, object value) method: add and modify, key, value.
        map.put("AA",123);
        map.put("BB",456);
        map.put("CC",789);
        //modify
        map.put("AA",342);

        System.out.println(map);


        Map map2 = new HashMap();
        map2.put("KK",453);
        map2.put("oo",2342);

        //map.putAll(Map map) method: store all key value pairs in m into the current map.
        map.putAll(map2);
        System.out.println(map);

        //map.remove(Object key) method: remove the key value pair of the specified key and return value.
        Object value = map.remove("CC");
        System.out.println(value);
        System.out.println(map);

        //map.clear() method: clear all data in the current map.
        map.clear();//be careful! Not null after emptying
        System.out.println(map);
    }

    @Test
    public void test2(){
        Map map = new HashMap();
        map.put("AA",123);
        map.put("BB",456);
        map.put("CC",789);

        //map.get(Object key) method: get the value corresponding to the specified key
        System.out.println(map.get("CC"));

        //map.containsKey(Object key) method: whether to include the specified key
        boolean isExist = map.containsKey("BB");
        System.out.println(isExist);

        //map.containsValue(Object value) method: whether to include the specified value
        boolean isExist2 = map.containsValue(456);
        System.out.println(isExist2);

        //map.size() method: returns the number of key value pairs in the map
        System.out.println(map.size());

        //map.isEmpty() method: judge whether the current map is empty
        System.out.println(map.isEmpty());

        //map.equals(Object obj) method: judge whether the current map and parameter object obj are equal
    }

}

Metaview method:

package com.holmes.java07;

import org.junit.Test;

import java.util.*;


public class MapTest {

    @Test
    public void test(){

        Map map = new HashMap();

        //Map. Put (object key, object value) method: add and modify, key, value.
        map.put("AA",123);
        map.put("BB",456);
        map.put("CC",789);
        //modify
        map.put("AA",342);

        System.out.println(map);


        Map map2 = new HashMap();
        map2.put("KK",453);
        map2.put("oo",2342);

        //map.putAll(Map map) method: store all key value pairs in m into the current map.
        map.putAll(map2);
        System.out.println(map);

        //map.remove(Object key) method: remove the key value pair of the specified key and return value.
        Object value = map.remove("CC");
        System.out.println(value);
        System.out.println(map);

        //map.clear() method: clear all data in the current map.
        map.clear();//be careful! Not null after emptying
        System.out.println(map);
    }

    @Test
    public void test2(){
        Map map = new HashMap();
        map.put("AA",123);
        map.put("BB",456);
        map.put("CC",789);

        //map.get(Object key) method: get the value corresponding to the specified key
        System.out.println(map.get("CC"));

        //map.containsKey(Object key) method: whether to include the specified key
        boolean isExist = map.containsKey("BB");
        System.out.println(isExist);

        //map.containsValue(Object value) method: whether to include the specified value
        boolean isExist2 = map.containsValue(456);
        System.out.println(isExist2);

        //map.size() method: returns the number of key value pairs in the map
        System.out.println(map.size());

        //map.isEmpty() method: judge whether the current map is empty
        System.out.println(map.isEmpty());

        //map.equals(Object obj) method: judge whether the current map and parameter object obj are equal
    }

    @Test
    public void test03(){
        Map map = new HashMap();
        map.put("AA",123);
        map.put("BB",456);
        map.put("CC",789);

        //Traverse all key sets: keySet()
        Set set = map.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }

        //Traverse all value sets: values()
        Collection values = map.values();
        Iterator iterator1 = values.iterator();
        while (iterator1.hasNext()){
            System.out.println(iterator1.next());
        }

        //Traverse all key value: entryset()
        Set entrySet = map.entrySet();
        Iterator iterator2 = entrySet.iterator();
        while (iterator2.hasNext()){
            Object obj = iterator2.next();
            //We need to turn around here!!!
            //All elements in the entry set collection are entries.
            Map.Entry entry = (Map.Entry)obj;
            System.out.println(entry.getKey() + "----->" + entry.getValue());
        }
        
    }

}

There are two ways to traverse a Set:

7.4 TreeMap class

Similarly, to add key value to TreeMap, the key must be an object created by the same class. You should also sort the keys: natural sorting and customized sorting.

Natural sorting:

package com.holmes.java07;

import org.junit.Test;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class TreeMapTest {

    @Test
    public void test(){

        TreeMap treeMap = new TreeMap();

        treeMap.put(new User2("Tom",22),50);
        treeMap.put(new User2("Aerry",24),23);
        treeMap.put(new User2("Mim",49),43);
        treeMap.put(new User2("Mim",36),78);
        treeMap.put(new User2("Jack",12),12);

        Set entrySet = treeMap.entrySet();
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            Map.Entry entry = (Map.Entry)obj;
            System.out.println(entry.getKey()+"-->"+entry.getValue());
        }
    }

}

class User2 implements Comparable{

    private String name;
    private int age;

    public User2(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) {
        //Sort by name from small to large
        if (o instanceof User2){

            User2 user2 = (User2)o;
            int compare = this.name.compareTo(user2.name);

            //If the names are the same size, compare the age
            if (compare != 0){
                return compare;
            }else {
                //Here is the compare method of Integer, remember!!
                return Integer.compare(this.age,user2.age);
            }

        }else {
            throw new RuntimeException("The types entered do not match");
        }
    }

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

Custom sorting:

package com.holmes.java07;

import org.junit.Test;

import java.util.*;

public class TreeMapTest {

    @Test
    public void test(){

        Comparator comparator = new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User2 && o2 instanceof User2){
                    User2 u1 = (User2)o1;
                    User2 u2 = (User2)o2;
                    return Integer.compare(u1.getAge(),u2.getAge());
                }else {
                    throw new RuntimeException("Type mismatch!");
                }
            }
        };

        TreeMap treeMap = new TreeMap(comparator);

        treeMap.put(new User2("Tom",22),50);
        treeMap.put(new User2("Aerry",24),23);
        treeMap.put(new User2("Mim",49),43);
        treeMap.put(new User2("Mim",36),78);
        treeMap.put(new User2("Jack",12),12);

        Set entrySet = treeMap.entrySet();
        Iterator iterator = entrySet.iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            Map.Entry entry = (Map.Entry)obj;
            System.out.println(entry.getKey()+"-->"+entry.getValue());
        }
    }

}

class User2{

    private String name;
    private int age;

    public User2(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 String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

7.5 Properties class

8. Collections tool class

First, collections are different from collections! Collection is the interface to create a collection; Collections is a tool class, which is responsible for operating collections and maps.

8.1 common tools

package com.holmes.java07;

import org.junit.Test;

import java.util.*;

public class CollectionsTest {

    @Test
    public void test(){

        List list = new ArrayList();
        list.add(123);
        list.add(233);
        list.add(23);
        list.add(23);
        list.add(23);
        list.add(73);
        list.add(93);
        list.add(0);

        //See how many times
        int frequency = Collections.frequency(list,23);
        System.out.println(frequency);


        //The copy method will encounter an exception: java.lang.IndexOutOfBoundsException: Source does not fit in dest
        //The exception is known from the source code that the length of dest is less than list.
        List dest = Arrays.asList(new Object[list.size()]);//This method is very good, which is equivalent to the number of null s in list.size.
        //Copy the set contents of the list to dest
        Collections.copy(dest,list);
        System.out.println(dest);

    }

}

8.2 common methods of collection synchronization control

package com.holmes.java07;

import org.junit.Test;

import java.util.*;

public class CollectionsTest {

    @Test
    public void test(){

        List list = new ArrayList();
        list.add(123);
        list.add(233);
        list.add(73);
        list.add(93);
        list.add(0);

        //The returned list1 is the thread safe List
        List list1 = Collections.synchronizedList(list);


        Map map = new HashMap();
        map.put("AA",123);
        map.put("BB",456);
        map.put("CC",789);
        //Similarly, map is also the same. map1 is thread safe
        Map map1 = Collections.synchronizedMap(map);


    }

}

Posted by thebighere on Sat, 27 Nov 2021 12:03:15 -0800