Set: Unordered, can not repeat element
|--hashset: The data structure is a hash table, and the thread is non-synchronous.
The principle of guaranteeing element uniqueness: Determining whether the hashcode value of an element is the same
If same, the Equals method of the element will continue to be judged, whether true
|--treeset: You can sort the elements in the Set collection
Note: When sorting, when the main conditions are the same, be sure to judge the secondary condition (otherwise it will be considered the same object without being added)
1 ImportJava.util.Iterator;2 ImportJava.util.TreeSet;3 4 /**5 * Requirements:6 * Store custom objects in TreeSet collection students7 * Want to sort by the age of the students8 */9 Public classPackagedemo {Ten One Public Static voidMain (string[] args) { ATreeSet ts=NewTreeSet (); -Ts.add (NewStudent ("Pikachu 1", 20)); -Ts.add (NewStudent ("Pikachu", 20)); theTs.add (NewStudent ("pickup", 19)); -Ts.add (NewStudent ("Racal", 21)); -Ts.add (NewStudent ("Racal", 21)); - +Iterator it=ts.iterator (); - + while(It.hasnext ()) { AStudent student=(Student) It.next (); atSystem.out.println (Student.getname () + "...." +student.getage ()); - } - - } - - } in classStudentImplementscomparable{//This interface forces students to have a comparative - PrivateString name; to Private intAge ; + PublicStudent (String name,intAge ) { - This. name=name; the This. age=Age ; * } $ PublicString GetName () {Panax Notoginseng returnname; - } the Public intGetage () { + returnAge ; A } the @Override + Public intcompareTo (Object o) { - if(NULL==o) { $ Throw NewRuntimeException ("Pass in an empty object"); $ } - if(! (OinstanceofStudent)) { - Throw NewRuntimeException ("Not in student class"); the } -Student student=(Student) o;Wuyi if( This.age>student.age) { the return1; -}Else if( This. age==student.age) { Wu return This.name.compareTo (student.name);///Note: When sorting, when the main conditions are the same, be sure to judge the secondary condition (otherwise it will be considered the same object without being added) - } About return-1; $ } - - -}
The TreeSet of Java Learning