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!!
Who is Participating?
sumanthpuvvulaAuthor Commented:
all Employee Objects are in a ArrayList ..... so I need to sort that arrayList based on the date object in Employee
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
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.


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


CEHJConnect With a Mentor Commented:
>>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

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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.