[JavaSE] Collection framework (TreeSet), javasetreeset
TreeSet: sorts the elements in the Set. By default, the elements are sorted by ascii table and the binary tree structure is used.
The left cross is small, and the right cross is large.
Store custom objects
Define a class Student to implement the Comparable class so that the custom class has a comparison
Define attribute age
Define attribute name
Implement the compareTo () method and pass in another Student object
If the age of the current Student object is greater than the age of another Student object, 1 is returned; otherwise-1 is returned.
Get Student object
Call the add () method of the TreeSet object. Parameter: Student object
Traverse a set
import java.util.TreeSet;public class TreeSetDemo { /** * @param args */ public static void main(String[] args) { TreeSet<Student> treeset=new TreeSet<Student>(); treeset.add(new Student("taoshihan1",30)); treeset.add(new Student("taoshihan2",20)); treeset.add(new Student("taoshihan3",40)); for(Student student:treeset){ System.out.println(student.name+"==="+student.age); } }}class Student implements Comparable<Student>{ public int age; public String name; public Student(String name,int age) { this.name=name; this.age=age; } @Override public int compareTo(Student o) { if(o.age<this.age){ return 1; }else{ return -1; } } }
Result:
Taoshihan2 === 20
Taoshihan1 = 30
Taoshihan3 = 40