How to sort List of User-defined type in Java?

Deadly 提交于 2020-01-16 03:31:08

问题


I'm currently learning how to work with Lists in Java. I've come across sorting Strings in a List by using Collections.sort() method and that works fine. However when I create a user-defined datatype, it doesn't sort and gives an error -

"no suitable method found for sort(List) method Collections.sort(List,Comparator) is not applicable (cannot instantiate from arguments because actual and formal argument lists differ in length) method Collections.sort(List) is not applicable (inferred type does not conform to declared bound(s) inferred: Child bound(s): Comparable) where T#1,T#2 are type-variables: T#1 extends Object declared in method sort(List,Comparator) T#2 extends Comparable declared in method sort(List)"

How can I sort the elements for a user-defined type?

Here is the code -

CODE -

package works;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;

class Child 
{
private String name;
public Child(String name)
{
    this.name=name;
}
@Override
public String toString()
{
    return name;
}
}
class LOL
{
void Meth()
{
    Child s1 = new Child("Hi");
    Child s2 = new Child("Bye");
    Child s3 = new Child("And");
    List<Child> f1 = Arrays.asList(s1,s2,s3);
    System.out.println(f1);
    System.out.println();
    Collections.sort(f1);  // This line is the erroneous line.
}
}
public class SortColl
{
public static void main(String X[])
{
    LOL l = new LOL();
    l.Meth();

}
}

回答1:


Implement Comparable in the Child class

class Child implements Comparable<Child>{
    private String name;

    public Child(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

    @Override
    public int compareTo(Child child) {
        return name.compareTo(child.name);
    }
}



回答2:


To sort a collection of any object, one of the following must be true:

  1. The object must implement Comparable. In this case, implement Comparable<Child>. Then Collections.sort will be able to sort using the compareTo method.
  2. Create your own class that implements Comparator, specifically Comparator<Child>, and pass an instance of that class as the second parameter to Collections.sort. Then the sorting algorithm will use the Comparator to sort the collection.


来源:https://stackoverflow.com/questions/18407784/how-to-sort-list-of-user-defined-type-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!