如何在Java中对用户定义类型的列表进行排序? [英] How to sort List of User-defined type in Java?

查看:34
本文介绍了如何在Java中对用户定义类型的列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习如何在 Java 中使用列表.我遇到过使用 Collections.sort() 方法对列表中的字符串进行排序,并且效果很好.但是,当我创建用户定义的数据类型时,它不会排序并给出错误 -

"没有找到适合 sort(List) 的方法方法 Collections.sort(List,Comparator) 不适用(不能从参数实例化,因为实际和形式参数列表的长度不同)方法 Collections.sort(List) 不适用(推断类型不符合声明的边界)推断:孩子界限:可比)其中 T#1,T#2 是类型变量:T#1 扩展在 sort(List,Comparator) 方法中声明的对象T#2 扩展了在 sort(List) 方法中声明的 Comparable"

如何对用户定义类型的元素进行排序?

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 -

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

}
}

推荐答案

实施 ComparableChild

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

这篇关于如何在Java中对用户定义类型的列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆