The first part:
Create Student Class
public class Student implements comparable<student> {
Member variables
private String name;
private int age;
Construction method
Public Student () {
Super ();
}
Public Student (String name, int.) {
THIS.name = name;
This.age = age;
}
Member Methods
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
@Override
Public String toString () {
Return "student{" +
"Name=" + name + ' \ ' +
", age=" + Age +
‘}‘;
}
@Override
public int CompareTo (Student set) {
Sort by age, main condition (uniqueness)
int num = this.age-set.age;
The same age, but different names, not the same element, so determine whether the name is the same.
int num2 = Num==0?this.name.compareto (set.name): num;
return num2;
}
}
Part II:
public class Tree {
public static void Main (string[] args) {
Create a Collection
treeset<student> set = new treeset<> ();
adding elements
Student S1 = new Student ("Mammy", 55);
Student s2 = new Student ("Little Swallow", 45);
Student s3 = new Student ("Crape Myrtle", 50);
Student S4 = new Student ("Five elder brother", 55);
Student S5 = new Student ("Er kang", 60);
Student s6 = new Student ("Er tai", 58);
Student s7 = new Student ("Shangjian", 55);
Student s8 = new Student ("Er tai", 58);
Add elements to the collection
Set.add (S1);
Set.add (S2);
Set.add (S3);
Set.add (S4);
Set.add (S5);
Set.add (S6);
Set.add (S7);
Set.add (S8);
for (Student X:set) {
SYSTEM.OUT.PRINTLN (x);
}
}
}
Output Result:
Small Swallow-----45
Crape Myrtle-----50
Five elder brother-----55
Mama-----55
Shangjian-----55
Thamel-----58
Seoul Kang-----60
TreeSet Custom Object Traversal case (natural sort)