TreeSet Custom Object Traversal case (natural sort)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.