开发者

How to sort linkedlist on some natural order?

开发者 https://www.devze.com 2023-02-28 18:04 出处:网络
We have a linkedlist, the elements of this linkedlist are Employee, I want to sort this linkedlist based on the salary of Employee, salary is one member of Em开发者_运维知识库ployee Class, can we use

We have a linkedlist, the elements of this linkedlist are Employee, I want to sort this linkedlist based on the salary of Employee, salary is one member of Em开发者_运维知识库ployee Class, can we use Collections.sort()? if not, how can I sort it? Can anyone explain me?


Yes, you can use Collections.sort()

You need to have your Employee class implement the Comparable interface.

http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html

In your compareTo() method you would compare the salary of the current object to that of the object passed in.

Edit:

The other option you have if you don't want that to be the default comparison is to create a Comparator object and use the second form -> Collections.sort(List, Comparator);

It would look like this:

class SalaryComparator implements Comparator<Employee>
{

    public int compare(Employee e1, Employee e2)
    {

        if (e1.getSalary() > e2.getSalary())
            return 1;
        else if (e1.getSalary() < e2.getSalary())
            return -1;
        else
            return 0;
    }

}

Now you can do: Collections.sort(myEmployeeList, new SalaryComparator());


While a LinkedList<Employee> will work, I'd use an ArrayList<Employee> for this:

List<Employee> employees = new ArrayList<Employee>();

After you populate it (either way) you can sort it by salary like so:

Collections.sort(employees, new Comparator<Employee>() {
    public int compare(Employee e1, Employee e2) {
        return e1.getSalary() - e2.getSalary();
    }
});


You can use Collections.sort()

But in order to do that, your Employee class needs to implement the Comparable interface first.

A rough example would be:

public class Employee implements Comparable<Employee>
{
    public int compareTo(Employee e)
    {
        return this.salary - e.salary;
    }
}


You can sort a linked list, but it's not an efficient operation, especially if the list is not trivial in size. Choose appropriate data structures.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号