MyClass不能转换为java.lang.Comparable:java.lang.ClassCastException

编程入门 行业动态 更新时间:2024-10-27 02:22:46
本文介绍了MyClass不能转换为java.lang.Comparable:java.lang.ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的项目中的类(简化):

我正在做一个java项目,我遇到这个问题,不知道如何解决它。 p>

public class Item { private String itemID; 私人整数价格; public Integer getPrice(){ return this.price; } } public class Store { private String storeID; private String address; } public class Stock { private Item item; 私人店铺; private整数itemCount; public Integer getInventoryValue(){ return this.item.getPrice()* this.itemCount; } }

然后我尝试排序一个 ArrayList 的股票,所以我创建另一个类叫$ code> CompareByValue

public class CompareByValue implements Comparator< Stock> { @Override public int compare(stock stock1,stock stock2){ return(stock1.getInventoryValue() - stock2.getInventoryValue()); }

}

当我尝试运行程序时,会出现错误:

线程main中的异常java.lang.ClassCastException任何人都知道有什么问题?/ b>

=h2_lin>解决方案

这是因为库存不实现可比较的。实现它:

public class库存实现可比较&库存> { public int compareTo(Stock o){ // ... } }

...或将 CompareByValue 的实例作为参数传递给 sort() 方法:

Collections.sort(list,new CompareByValue());

I am doing a java project and I got this problem and don't know how to fix it.

The classes in my project (simplified):

public class Item { private String itemID; private Integer price; public Integer getPrice() { return this.price; } } public class Store { private String storeID; private String address; } public class Stock { private Item item; private Store store; private Integer itemCount; public Integer getInventoryValue() { return this.item.getPrice() * this.itemCount; } }

Then I try to sort an ArrayList of Stock so I create another class called CompareByValue

public class CompareByValue implements Comparator<Stock> { @Override public int compare(Stock stock1, Stock stock2) { return (stock1.getInventoryValue() - stock2.getInventoryValue()); }

}

When I try to run the program, it gives the error:

Exception in thread "main" java.lang.ClassCastException: Stock cannot be cast to java.lang.Comparable

Anyone know what's wrong?

解决方案

It's because Stock isn't implementing Comparable. Either implement it:

public class Stock implements Comparable<Stock> { public int compareTo(Stock o) { // ... } }

... Or pass an instance of CompareByValue as parameter to the sort() method:

Collections.sort(list, new CompareByValue());

更多推荐

MyClass不能转换为java.lang.Comparable:java.lang.ClassCastException

本文发布于:2023-10-31 05:16:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545116.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   java   MyClass   ClassCastException   Comparable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!