java排序器_如何使用Java中的比较器进行排序

这篇博客探讨了在Java中使用比较器进行对象排序时遇到的ClassCastException问题。作者提供了一个尝试对People类进行排序的代码示例,但遇到了错误。错误提示表明无法将People对象转换为Comparable。博客内容可能涉及如何正确实现Comparable接口或Comparator类以解决此类问题,以及如何调整代码以避免类型转换异常。
摘要由CSDN通过智能技术生成

如何使用Java中的比较器进行排序

我学会了如何使用比较器,但我在使用比较器时遇到了困难。我的代码中有一个错误:Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable

at java.util.Arrays.mergeSort(Unknown Source)

at java.util.Arrays.sort(Unknown Source)

at java.util.Collections.sort(Unknown Source)

at New.TestPeople.main(TestPeople.java:18)

这是我的代码:import java.util.Comparator;public class People implements Comparator {

private int id;

private String info;

private double price;

public People(int newid, String newinfo, double newprice) {

setid(newid);

setinfo(newinfo);

setprice(newprice);

}

public int getid() {

return id;

}

public void setid(int id) {

this.id = id;

}

public String getinfo() {

return info;

}

public void setinfo(String info) {

this.info = info;

}

public double getprice() {

return price;

}

public void setprice(double price) {

this.price = price;

}

public int compare(Object obj1, Object obj2) {

Integer p1 = ((People) obj1).getid();

Integer p2 = ((People) obj2).getid();

if (p1 > p2) {

return 1;

} else if (p1 

return -1;

} else {

return 0;

}

}}import java.util.ArrayList;import java.util.Collections;public class TestPeople {

public static void main(String[] args) {

ArrayList peps = new ArrayList();

peps.add(new People(123, "M", 14.25));

peps.add(new People(234, "M", 6.21));

peps.add(new People(362, "F", 9.23));

peps.add(new People(111, "M", 65.99));

peps.add(new People(535, "F", 9.23));

Collections.sort(peps);

for (int i = 0; i 

System.out.println(peps.get(i));

}

}}

我相信它必须在比较法中对铸件做些什么,但我只是在玩弄它,仍然找不到解决的办法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值