table of Contents
I. Introduction
II. TreeMap inheritance of
three, SortedMap Interface source code parsing
3.1 SortedMap Interface
3.2 Comparable Interface
3.3 Comparator interfaces
four, NavigableMap Interface source code parsing
V. Summary
I. Introduction
In the two previous essay we mentioned, when the HashMap barrel is too large, the list will automatically be converted into a red-black tree structure, when a passing, because we will stay in this chapter, a detailed understanding for the TreeMap.
Second, the inheritance of TreeMap
Let's start with a look at TreeMap inheritance, it has a general understanding:
You can see, in addition to the prior HashMap in common inherited classes and interfaces, TreeMap implements NavigableMap interface, and NavigableMap inherited from SortedMap, it can be seen from the name, just a sort of interface used. This is also the reason why the TreeMap sorting can be achieved. Due to space relations, the source TreeMap resolve divided into three parts, this chapter will NavigableMap interfaces and SortedMap resolution.
Three, SortedMap Interface source code parsing
3.1 SortedMap Interface
public interface a SortedMap <K, V> the extends the Map <K, V> { // return key for sorting comparator performs, if this map uses natural ordering of its key was null Comparator <? Super K> Comparator (); // return from the map to fromKey between (including) toKey to (not including) a SortedMap <K, V> the subMap (K to fromKey, toKey K); // return of less than toKey map a SortedMap <K, V> headMap, (K toKey); // return of greater than or equal fromKey map a SortedMap <K, V> tailMap (K fromKey); // returns the map in the first (lowest) key K firstKey (); // returns the last map (highest) key K lastKey (); Set<K> keySet(); Collection<V> values(); Set<Map.Entry<K, V>> entrySet(); }
SortedMap interface is relatively simple, not very special place, the only special feature of this interface is to return Comparator, it is conceivable to realize the secret of sorting perhaps hidden in here. Let us look Comparator and Comparable interface, little correlation between the two, you can understand the comparison function comes to Comparable, Comparator and is given the ability to target a relatively no comparison capabilities. Here is a simple example: the face of a calculation problems, small mouth tomorrow raw computing power is very strong, at a glance work out the answer. And Mike Without this capability, you need a calculator to answer.
3.2 Comparable Interface
Let us look at its code:
public interface the Comparable <T> { // if o is less than, returns negative; o equal, returns 0; returns a positive number greater than o. public int the compareTo (T O); }
Yes, that's so simple, inside pass a generic object o T a, o to compare. O is less than, returns negative; o equal, returns 0; returns a positive number greater than o.
We are familiar with many objects, such as String
, Integer
, Double
and so implements this interface. We can look at a simple example:
public class Item implements Comparable<Item> { private String name; private int price; public Item(String name, int price) { this.name = name; this.price = price; } public int getPrice() { return price; } public String getName() { return name; } @Override public String toString() { return "Item{" + "name='" + name + '\'' + ", price=" + price + '}'; } @Override public int compareTo(Item o) { if (this.name.compareTo(o.name) < 0) { return -1; } else if (this.name.compareTo(o.name) > 0) { return 1; } else { return 0; } } public static void main(String[] args) { List<Item> items = Arrays.asList(new Item("banana", 200), new Item("apple", 400)); System.out.println("before:" + items); Collections.sort(items); System.out.println("after:" + items); } }
Above the main function output:
before:[Item{name='banana', price=200}, Item{name='apple', price=400}]
after:[Item{name='apple', price=400}, Item{name='banana', price=200}]
In the above example, we realize his Comparable interface, comparing the name attribute of the Item, and then it is sorted by Collections.sort (Notably: Comparable interface object does not implement the method can not be used) . But if I do not want to sort it by name property, you want to sort of price it, or to sort of name, the same words in a sort of price it, do not use this would not be able to achieve it. This requires reference to the following Comparator
interfaces
3.3 Comparator Interface
As usual first look at the code:
@FunctionalInterface public interface Comparator <T> { // Core method used to compare two objects, if less than o1 o2, returns negative; o2 equal, returns 0; o2 returns a positive number greater than int Compare (T o1, o2 T); // seems rarely used, usually with the object comes the equals boolean the equals (Object obj); / ** ----------- The following are the new JDK1.8 interfaces, pick a few to put ---------- * / // Returns the inverse sorting comparator default Comparator <T> the reversed () { return Collections.reverseOrder ( the this ); } // under the name know, after the first conducted compare compare to conduct a comparative default Comparator <T> thenComparing (Comparator <? Super T> OTHER) { Objects.requireNonNull(other); return (Comparator<T> & Serializable) (c1, c2) -> { int res = compare(c1, c2); return (res != 0) ? res : other.compare(c1, c2); }; } // of type int key compares public static <T> Comparator <T> comparingInt (ToIntFunction <? Super T> keyExtractor) { Objects.requireNonNull(keyExtractor); return (Comparator<T> & Serializable) (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2)); } // return the normal sequence comparator public static <T the extends the Comparable <? Super T >> Comparator <T> NaturalOrder () { return (Comparator <T> ) Comparators.NaturalOrderComparator.INSTANCE; } }
With the view of how to use, first look at JDK1.8 previous usage:
public class SimpleComparator implements Comparator<Item> { @Override public int compare(Item o1, Item o2) { return o1.price - o2.price; } public static void main(String[] args) { List<Item> items = Arrays.asList(new Item("banana", 200), new Item("apple", 400), new Item("Orange", 100)); Collections.sort(items, new SimpleComparator()); System.out.println(items); } }
The output of the main function is:
[Item{name='Orange', price=100}, Item{name='banana', price=200}, Item{name='apple', price=400}]
JDK1.8 previous usage to achieve their manual Comparator interface, and then call Collections.sort()
, the incoming class to achieve complete ordering, very troublesome, it is relatively simple and JDK1.8 a lot:
public static void main(String[] args) { List<Item> items = Arrays.asList(new Item("banana", 200), new Item("apple", 400), new Item("Orange", 100)); Collections.sort(items, (Item a, Item b) -> a.price - b.price); System.out.println(items); }
Even, we can not use Collections.sort:
public static void main(String[] args) { List<Item> items = Arrays.asList(new Item("banana", 100), new Item("Orange", 100), new Item("apple", 400), new Item("Orange", 50)); items.sort((Item a, Item b) -> a.price - b.price); System.out.println(items); //使用上面的thenComparing items.sort(Comparator.comparing(Item::getName).thenComparing(Comparator.comparingInt(Item::getPrice))); System.out.println("after using thenComparing: " + items); }
Above the main function output:
[Item{name='orange', price=50}, Item{name='banana', price=100}, Item{name='orange', price=100}, Item{name='apple', price=400}] after using thenComparing: [Item{name='apple', price=400}, Item{name='banana', price=100}, Item{name='orange', price=50}, Item{name='orange', price=100}]
Four, NavigableMap Interface source code parsing
public interface NavigableMap <K, V> the extends a SortedMap <K, V> { // return key as the nearest Key (not included equal to) the key-value pair does not return null of Map.Entry <K, V> lowerEntry (Key K ); // return key as the nearest (not included equal) key returns no null K lowerKey (key K); // return key is less than and closest to (including equal to) key key-value pair does not return null the Map .Entry <K, V> floorEntry (key K); // returns smaller than and closest to (including equal to) the key key, does not return null K floorKey (key K); // returns greater than and closest to (including equal to) to given key value pairs did not return null of Map.Entry <K, V> ceilingEntry, (K key); // supra K ceilingKey (K key); // returns greater than and closest to (without equivalent) of a given key key-value pair Map.Entry <K, V>higherEntry (Key K); // supra K higherKey (Key K); // returns first the Entry of Map.Entry <K, V> firstEntry (); // Returns the last the Entry of Map.Entry <K, V> lastEntry, (); // removes and returns the first the Entry of Map.Entry <K, V> pollFirstEntry (); // supra of Map.Entry <K, V> pollLastEntry (); // returns mapping relationship map contained in reverse view NavigableMap <K, V> the descendingMap (); // returns NavigableSet view of the keys contained in the map. iterator set in ascending order of the key a NavigableSet <K> navigableKeySet (); // reverse a NavigableSet <K> descendingKeySet (); //The toKey fromKey and to return the child map, two boolean parameter contains the Key NavigableMap <K, V> the subMap (K fromKey, boolean fromInclusive, ToKey K, Boolean toInclusive); // returns is less than (or equal to, according inclusive) map toKey of NavigableMap <K, V> headMap, (K toKey, Boolean Inclusive); // returns greater than (or equal to, map inclusive) fromKey according NavigableMap <K, V> tailMap (K to fromKey, Boolean Inclusive); SortedMap<K,V> subMap(K fromKey, K toKey); SortedMap<K,V> headMap(K toKey); SortedMap<K,V> tailMap(K fromKey); }
Note: the return of the map and the original map affect each other.
V. Summary
This chapter analyzes the inheritance TreeMap, giving back analysis TreeMap as bedding. SortedMap and NavigableMap of interfaces, including a number of methods that return Map, which is a major feature as a sort Map it.