TreeSet custom sorting and natural sorting

Source: Internet
Author: User
Tags comparable sorted by name

Some of the major features of TreeSet:
1. The type stored in TreeSet must be consistent, cannot save int, and then save string
2, TreeSet in the traversal of the collection elements, is the order of "from small to large" (my understanding, if the letters stored, sorted by dictionary order)
3, Sort: When adding custom objects to TreeSet, there are 2 sorting methods, 1: Natural sort 2, custom sort
Natural sorting: Requires the custom class to implement the Java.lang.Comparable interface and override the CompareTo (Object obj) method. In this method, indicate which property of the custom class to sort by

Example of a natural sort:
1. Define a Class (employee in article) implement comparable interface
2. Rewrite the CompareTo () method in the comparable interface
3. Sort by the specified attribute in CompareTo () (the article is sorted by name)
code example:
Employee class
public class Employee implements comparable{
public int compareTo (Object o) {
if (o instanceof Employee) {
Employee E = (employee) O;
Return This.name.compareTo (e.name);
}
return 0;
}

private String name;
private int age;
Private MyDate birthday;

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;
}

Public MyDate Getbirthday () {
return birthday;
}

public void Setbirthday (mydate birthday) {
This.birthday = Birthday;
}

Public Employee (String name, Int. age, mydate birthday) {
THIS.name = name;
This.age = age;
This.birthday = Birthday;
}

@Override
Public String toString () {
Return "employee{" +
"Name=" + name + ' \ ' +
", age=" + Age +
", birthday=" + Birthday +
‘}‘;
}

@Override
public boolean equals (Object o) {
if (this = O) return true;
if (o = = NULL | | getclass ()! = O.getclass ()) return false;

Employee employee = (employee) O;

if (age! = Employee.age) return false;
if (name! = null?!name.equals (employee.name): Employee.Name! = null) return false;
return birthday! = null? Birthday.equals (employee.birthday): Employee.birthday = = null;
}

@Override
public int hashcode () {
int result = name! = null? Name.hashcode (): 0;
result = * result + age;
result = * result + (Birthday! = null? Birthday.hashcode (): 0);
return result;
}
}

Test class
 public class Treesettest {
public static void Main (string[] args) {
test1 ();

/**
* Natural sort Sort by name so your employee must implement the comparable interface
*/
public static void Test1 () {
Employee e1 = new Employee ("Liudehua", 55,new mydate (4,12,1997));
Employee e2 = new Employee ("One", 55,new mydate (5,12,1997));
Employee E3 = new Employee ("55,new", MyDate (6,12,1997));
Employee e4 = New Employee ("55,new", MyDate (7,12,1997));
Employee e5 = new Employee ("55,new", MyDate (8,12,1997));
TreeSet set = new TreeSet ();
Set.add (E1);
Set.add (E2);
Set.add (E3);
Set.add (E4);
Set.add (E5);

Iterator i = Set.iterator ();
while (I.hasnext ()) {
System.out.println (I.next ());
}
}
}
The output results are sorted by name. In alphabetical order

ii. Custom sorting example
Employee1 class
public class Employee1 {
private String name;
private int age;
Private MyDate birthday;

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;
}

Public MyDate Getbirthday () {
return birthday;
}

public void Setbirthday (mydate birthday) {
This.birthday = Birthday;
}

Public Employee1 (String name, Int. age, mydate birthday) {
THIS.name = name;
This.age = age;
This.birthday = Birthday;
}

@Override
Public String toString () {
Return "employee{" +
"Name=" + name + ' \ ' +
", age=" + Age +
", birthday=" + Birthday +
‘}‘;
}

@Override
public boolean equals (Object o) {
if (this = O) return true;
if (o = = NULL | | getclass ()! = O.getclass ()) return false;

Employee1 employee = (Employee1) o;

if (age! = Employee.age) return false;
if (name! = null?!name.equals (employee.name): Employee.Name! = null) return false;
return birthday! = null? Birthday.equals (employee.birthday): Employee.birthday = = null;
}

@Override
public int hashcode () {
int result = name! = null? Name.hashcode (): 0;
result = * result + age;
result = * result + (Birthday! = null? Birthday.hashcode (): 0);
return result;
}
}

MyDate class
public class MyDate {
private int day;
private int month;
private int year;

public int GetDay () {
Return day;
}

public void Setday (Int. day) {
This.day = day;
}

public int GetMonth () {
Return month;
}

public void setmonth (int month) {
This.month = month;
}

public int getYear () {
Return year;
}

public void Setyear (int. year) {
This.year = year;
}

Public mydate (int day, int month, int) {
This.day = day;
This.month = month;
This.year = year;
}

@Override
Public String toString () {
Return "mydate{" +
"day=" + Day +
", month=" + month +
", year=" + year +
‘}‘;
}

Override the Equals () and Hashcode () methods of mydate before overriding the

@Override
public boolean equals (Object o) {
if (this = O) return true;
if (o = = NULL | | getclass ()! = O.getclass ()) return false;

MyDate mydate = (mydate) o;

if (day! = Mydate.day) return false;
if (Month! = Mydate.month) return false;
Return year = = Mydate.year;
}

@Override
public int hashcode () {
int result = day;
result = * result + month;
result = * result + year;
return result;
}
}

Test Class
public class TreeSetTest1 {
public static void Main (string[] args) {
Test2 ();
}
/**
* Custom Sort by the designated birthday to row
*/
public static void Test2 () {
ComparatorComparator= new Comparator () {
public int Compare (object O1, Object O2) {
if (O1 instanceof Employee1 && O2 instanceof Employee1) {
Employee1 e1 = (Employee1) O1;
EMPLOYEE1 e2 = (Employee1) O2;

MyDate birth1 = E1.getbirthday ();
MyDate birth2 = E2.getbirthday ();

if (birth1.getyear () = Birth2.getyear ()) {
The defined type is int so use the "-" minus sign instead of CompareTo ()
Return Birth1.getyear ()-birth2.getyear ();
} else {
if (birth1.getmonth () = Birth2.getmonth ()) {
Return Birth1.getmonth ()-Birth2.getmonth ();
} else {
Return Birth1.getday ()-Birth2.getday ();
}
}
}
return 0;
}
};

"Be sure to indicate that you are comparing comparator parameters by specific objects."
TreeSet set = new TreeSet (Comparator);
Employee1 e1 = new Employee1 ("Liudehua", 55,new mydate (5,8,1990));
EMPLOYEE1 e2 = new Employee1 ("One", 55,new mydate (5,11,1997));
Employee1 E3 = new Employee1 ("n", 55,new mydate (6,10,1997));
Employee1 e4 = new Employee1 ("n", 55,new mydate (7,9,1997));
Employee1 e5 = new Employee1 ("$", 55,new mydate (8,8,1997));
Set.add (E1);
Set.add (E2);
Set.add (E3);
Set.add (E4);
Set.add (E5);

Iterator i = Set.iterator ();
while (I.hasnext ()) {
System.out.println (I.next ());
}
}
}


Summary:
The natural sort implements the comparable interface. It is used when the class can be modified.

The custom sort implementation is the comparator interface. It is used when the class is not modified

When using custom sorting or natural sorting, the hashcode () and Equals () methods are overridden in the class they are used in


The difference between comparable and comparator:[Reference blog: http://blog.csdn.net/excellentyuxiao/article/details/52344594]
Comparator under the Util bag, comparable under the Lang bag. The ordering of objects in Java is standard with the comparable interface. Comparator is the implementation of sorting outside the object.


TreeSet custom sorting and natural sorting

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.