Java Collection This piece is used more in the work, some things always forget, so record down here. TreeSet principle
1. Features
- TreeSet are used for sorting, you can specify a sequence in which the objects are stored in the order specified
2. How to use
- A. natural order (comparable)
- The Add () method of the TreeSet class promotes the stored object to the comparable type
- The CompareTo () method of the calling object is compared to the object in the collection ( who is currently credited, who will call the CompareTo method )
- Stored according to the results returned by the CompareTo () method
- B. Comparator order (Comparator)
- Create a treeset when you can make a comparator
- If a subclass object of comparator is passed in, the TreeSet is sorted in the order of the comparator
- The Add () method internally calls the Compare () method in the comparator interface to sort
- The object being called (that is, the currently deposited object) is the first parameter of the Compare method, and the object in the collection (the object that has been added) is the second parameter of the Compare method
- C. Two different ways of difference
- TreeSet constructors do not pass anything, by default in the order of comparable in the class (no error ClassCastException)
- TreeSet if the comparator is passed in, priority is given to comparator
TreeSet Sort Related Summary