• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 432
  • Last Modified:

Object Sorting

import java.util.*;
public class Employee{
Date DOB = new Date(0L);
}

I have different Employee objects with different DOB's. I want to sort Employee object based on DOB field. How to do that? Please suggest with the detailed explanation!!
0
sumanthpuvvula
Asked:
sumanthpuvvula
2 Solutions
 
sumanthpuvvulaAuthor Commented:
all Employee Objects are in a ArrayList ..... so I need to sort that arrayList based on the date object in Employee
0
 
for_yanCommented:
You just override compareTo method for your class Employee and then Collections.sort(ArrayList) will work fo you.
I'll preprae some code for you
0
 
for_yanCommented:
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
objectsCommented:
0
 
for_yanCommented:

Well, the exmample above in fact uses your case with Employee and dates.
Basically you need to add to your class definition "implements Comparable"
and then add method int compare (Employee e1, Employee e2) as shown below.

That would be enough then after Collections.sort(al);
where al is ArrayList of your employyee, thelist al will become sorted

public class Employee implements Comparable {

    public int compare(Employee e1, Employee e2) {
        int dateCmp = e2.hireDate().compareTo(e1.hireDate());
        if (dateCmp != 0)
            return dateCmp;
        return (e1.number() < e2.number() ? -1 :
                (e1.number() == e2.number() ? 0 : 1));
    }

}



}
0
 
CEHJCommented:
>>I want to sort Employee object based on DOB field. How to do that?

If you're using Comparable, you just need
public class Employee implements Comparable<Employee> {
...
	public int compare(Employee e1, Employee e2) {
		return e1.DOB.compareTo(e2.DOB);
	}

}

Open in new window

0
 
DhaestCommented:
This question has been classified as abandoned and is being closed as part of the Cleanup Program. See my comment at the end of the question for more details.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now