问题
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:
- The object must implement Comparable. In this case, implement
Comparable<Child>
. ThenCollections.sort
will be able to sort using thecompareTo
method. - Create your own class that implements Comparator, specifically
Comparator<Child>
, and pass an instance of that class as the second parameter toCollections.sort
. Then the sorting algorithm will use theComparator
to sort the collection.
来源:https://stackoverflow.com/questions/18407784/how-to-sort-list-of-user-defined-type-in-java