在方法petInteraction()中,我希望在运行代码时通过情感级别对宠物进行排序,这样用户可以选择首先处理哪个宠物。目前我已经包含了一个新方法sort(),但它导致了一个错误。
我正在使用eclipse,错误是:
Exception in thread "main" java.lang.ClassCastException: [I 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 AlienPetSort.sort(AlienPetSort.java:46)
at AlienPetSort.main(AlienPetSort.java:13)
有关如何解决这个问题的建议吗?
答案 0 :(得分:2)
您正在尝试运行Arrays.sort(EmotionalState);
,但EmotionalState
是一个二维数组。您可以使用Comparator
对该二维数组进行排序,但我不相信Arrays
支持多个维度 - 这是我在Google快速搜索中找到的一个示例:{{3 }}
快速查看您的代码设计,我认为您可以很好地定义Pet对象并为其提供特定的情感状态值,而不是尝试将其全部保存在二维数组中。特别是如果您计划继续为代码添加更多内容,那么至少需要一个小型的重构工作!
答案 1 :(得分:2)
private static int[][] EmotionalState = new int[2][3];
.
.
Arrays.sort(EmotionalState);
鉴于以上几点。 Arrays.sort将一维数组作为参数,并传入一个二维数组。
答案 2 :(得分:0)
您无法使用普通Arrays.sort
对二维数组进行排序。要对二维数组进行排序,请使用Comparator
,
private static int[][] EmotionalState = new int[2][3];
....
Arrays.sort(EmotionalState, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return o1[0] - o2[0];
}
});