TreeSet is the only implementation class for SortedSet, as the SortedSet name implies,TreeSet allows the collection element to be in the orderly state.
Compared with HashSet, TreeSet also provides the following methods (listed, mixed face cooked:)
SortedSet subset (Object fromelement,object toelement): Returns the subset of this set, ranging from fromelement (inclusive) to Toelement (not included)
SortedSet HeadSet (Object toelement): Returns the subset of this set, which is less than the subset of toelement
SortedSet Tailset (Object fromelement): Returns the subset of this set with a range greater than or equal to fromelement the subset
Object First (): return This set of the first element
Object Last (): strong> return This set last element
Object Lower ( Object e ) : strong> returns less than specified The largest element in the collection
Object Higher ( Object e ) : strong> return greater than specified The smallest element in the collection
"None of the above reference elements need to be in the collection. "
To summarize, the last four methods are to find the first, previous, next, and last element in the collection. At the same time the first three are the eligible subsets that return the set.
PackageTest01;ImportJava.util.TreeSet; Public classTesttreeset { Public Static voidMain (string[] args) {TreeSet num=NewTreeSet (); Num.add (2); Num.add (-2); Num.add (10); Num.add (9); SYSTEM.OUT.PRINTLN (num); //See: Not in the order of addition, is the number from small to large sortSystem.out.println (Num.first ());//See: Numbers from small to large sort the firstSystem.out.println ("9 to 12" +num.subset (9, 12)); System.out.println ("Smaller than 8" +num.headset (8)); System.out.println ("Bigger than 8" +num.tailset (8));}}
And HashSet uses the hash algorithm to determine the storage location of the element, TreeSet The data of the red-black Tree (pending) to store the collection elements. So what's his sort of rule?
Natural sort (default).
Custom sorting.
Cond....
Java Set TreeSet detailed