gpt4 book ai didi

java - 不能转换为 java.lang.Comparable

转载 作者:IT老高 更新时间:2023-10-28 21:09:07 26 4
gpt4 key购买 nike

import java.util.HashMap;
import java.io.*;
import java.util.*;
public class Fegan implements Comparable{
HashMap<String, Integer> cart = new HashMap<String, Integer>();
List list = new ArrayList<FoodItems>();
int x =0;
public void addToCart(FoodItems f)
{
cart.put(f.name, f.valueOfFood);
}
public String display(FoodItems f)
{
return(f.name + " costs " + f.valueOfFood);
}
public void addToList(FoodItems f)
{
//FoodItems temp = (FoodItems) f;
list.add(f);
}
public int compareTo(Object o)
{
//FoodItems temp = (FoodItems) o;
if(this.x == ((FoodItems)o).valueOfFood)
return 0;
else if (this.x <((FoodItems)o).valueOfFood)
return 1;
else
return -1;
}
public void sortMap(List list)
{
for(int i =0; i< list.size(); i++)
{
FoodItems temp = (FoodItems) list.get(i);
cart.put(temp.name, temp.valueOfItem);

}
}
}

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.io.*;
import java.util.*;
public class Test {
public static void main(String [] args)
{
HashMap<String, Integer> cart = new HashMap<String, Integer>();
FoodItems firts = new FoodItems("Chocolate" , 50);
FoodItems second = new FoodItems("Juice", 79);
FoodItems third = new FoodItems("Apple", 200);
FoodItems forth = new FoodItems("Orange", 300);
FoodItems fifth = new FoodItems("Milk" , 400);
ArrayList items = new ArrayList();
items.add(firts);
items.add(second);
items.add(third);
items.add(forth);
items.add(fifth);
Collections.sort(items);
Iterator itr = items.iterator();
Fegan myFegan = new Fegan();
myFegan.sortMap(items);

while(itr.hasNext()){
Object element = itr.next();
System.out.println(element + "\n");
}
}
}

为什么要写:

Exception in thread "main" java.lang.ClassCastException: FoodItems cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at Test.main(Test.java:21)

最佳答案

  • 实现Comparable的对象是Fegan

您在其中覆盖的方法 compareTo 应该有一个 Fegan 对象作为参数,而您将其转换为 FoodItems。您的 compareTo 实现应该描述一个 Fegan 与另一个 Fegan 的比较。

  • 要实际进行排序,您可能希望您的 FoodItems 也实现 Comparable 并在其中复制粘贴您的实际 compareTo 逻辑。

关于java - 不能转换为 java.lang.Comparable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8699195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com