TreeMap learning

1. Concept

public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable

TreeMap inherits AbstractMap, and AbstractMap implements the Map<K,V> interface. So TreeMap has the characteristics of Map. It is defined as follows:

	
    /**
     * The comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     * 比较器
     */
    
	private final Comparator<? super K> comparator;
	// 根节点
    private transient Entry<K,V> root;

    /**
     * The number of entries in the tree
     * 节点数量
     */
    private transient int size = 0;

    /**
     * The number of structural modifications to the tree.
     * 修改次数
     */
    private transient int modCount = 0;

The structure of Entry, a red-black binary tree node

		K key;
        V value;
        Entry<K,V> left;
        Entry<K,V> right;
        Entry<K,V> parent;
        boolean color = BLACK;

Features:

1. The underlying structure is a red-black binary tree, and the efficiency of adding, deleting, modifying and checking is relatively high
2. The keys are sorted by default, so the keys must implement one of natural sorting and custom sorting
3. The stored elements are unordered (meaning that the order of elements is inconsistent with the order of insertion)

4. The key is repeatedly overwritten, and the comparator returns 0 according to the specific sorting rules in the key, which has nothing to do with key.equals()
5. The key cannot be null (sorting is required)
5. Emphasis: When using the implementation class of the map interface, remember not to modify the attribute value of the key, otherwise the value corresponding to the key will not be found

If you want to use TreeMap to store data, you must be able to sort the keys, and there are two sorting methods
1. The natural sorting algorithm requires the class to implement the Comparable interface and rewrite the compareTo() method
2. Customize the sort Comparator, generally using an anonymous inner class

Two, examples

Example of Person class
Requires keys to be sortable, Person is sorted according to height
1. Person class does not implement the Comparable interface, an error is reported Person cannot be cast to java.lang.Comparable
2. Natural sorting, Person class implements the Comparable interface, rewrite compareTo() The method is sorted in ascending order of height
3. Customize the comparator and implement the anonymous class rewriting compare() method to sort in descending order of height

public class Person implements Comparable<Person>{
    
    
    String name;
    int high;

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

    public String toString(){
    
    
        return "Student{" +
                "name='" + name + '\'' +
                ", high=" + high +
                '}';
    }
    /*
        按照身高 升序
     */
    @Override
    public int compareTo(@NotNull Person person) {
    
    
       if(person.high > this.high){
    
    
           return -1;
       }else if(person.high < this.high) {
    
    
           return 1;
       }
       return 0;
    }
}

test:

/*
        key必须可排序, Person 按照身高进行排序
     */
    public static void test2() {
    
    

        log.info("1、Person 类未实现 Comparable 接口时报错  Person cannot be cast to java.lang.Comparable");
        log.info("2、Person 类实现 Comparable 接口,重写 compareTo()方法按照身高升序排序");
        //输出:
        // name:Student{name='小王', high=160}, high:88
        // name:Student{name='小张', high=170}, high:80
        // name:Student{name='小李', high=180}, high:90

        TreeMap<Person, Integer> personInfoMap = new TreeMap<>();
        personInfoMap.put(new Person("小张", 170), 80);
        personInfoMap.put(new Person("小王", 160), 88);
        personInfoMap.put(new Person("小李", 180), 90);

        for (Map.Entry<Person, Integer> personIntegerEntry : personInfoMap.entrySet()) {
    
    
            log.info("name:{}, high:{}", personIntegerEntry.getKey(),personIntegerEntry.getValue());
        }



        log.info("3、定制比较器,实现匿名类重写 compare()方法按照身高降序排序");
        //输出:
        // name:Student{name='小红', high=166}, high:80
        // name:Student{name='小芳', high=163}, high:90
        // name:Student{name='小丽', high=160}, high:88
        TreeMap<Person, Integer> personInfoMap1 = new TreeMap<>(new Comparator<Person>() {
    
    
            @Override
            public int compare(Person o1, Person o2) {
    
    
                if(o1.high > o2.high){
    
    
                    return -1;
                }else if(o1.high < o2.high){
    
    
                    return 1;
                }
                return 0;
            }
        });

        personInfoMap1.put(new Person("小红", 166), 80);
        personInfoMap1.put(new Person("小丽", 160), 88);
        personInfoMap1.put(new Person("小芳", 163), 90);

        personInfoMap1.forEach((k,value) ->{
    
    
            log.info("name:{}, high:{}", k,value);
        });
    }

Guess you like

Origin blog.csdn.net/Misszhoudandan/article/details/131481054