3 回答
TA贡献1851条经验 获得超3个赞
您需要首先检查其中一个堆栈是否比另一个短。如果不是,您需要比较对 的元素,list1而list2不是相反。
Collections.sort(arrayList, new Comparator<Stack<Integer>>(){
public int compare(Stack<Integer> list1, Stack<Integer> list2){
int result = Integer.compare(list1.size(), list2.size());
for (int i = 0; result == 0 && i < list1.size(); i++)
{
result = Integer.compare(list1.get(i), list2.get(i));
}
return result;
}
});
TA贡献1811条经验 获得超6个赞
如果我们的字典序概念是相同的,那么问题似乎在于您使用的是倒置的 compareTo(list2 compareTo list1 而不是 list1 compareTo list2)。
经过一些修改后,您的代码将如下所示:
Collections.sort(arrayList, new Comparator<Stack<Integer>>() {
public int compare(Stack<Integer> list1, Stack<Integer> list2) {
int result = 0;
for (int i = 0; i <= list1.size() - 1 && result == 0; i++) {
if (list2.size()-1 < i)
return 1;
else
result = list1.get(i).compareTo(list2.get(i));
}
return result;
}
});
此代码将产生以下结果:[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 3], [1, 1, 1, 3, 1], [1, 1, 3, 1, 1], [1, 1, 3, 3], [1, 3, 1, 1, 1], [1, 3, 1, 3], [1, 3, 3, 1], [1, 4, 4], [3, 1, 1, 1, 1], [3, 1, 1, 3], [3, 1, 3, 1], [3, 3, 1, 1], [3, 3, 3], [4, 1, 4], [4, 4, 1]],尽管您的预期结果我理解为按字典顺序排列。
在if (list2.size()-1 < i)由于list2中比list1的较小for循环内防止IndexOutOfBoundsException异常。
TA贡献1827条经验 获得超9个赞
由于这是一项任务,我会将您放在我认为正确的方向上,但我不会为您解决编程问题:
compare()
是在接口Comparator<T>
中定义的一个方法,它应该-1, 0, or 1
根据作为参数传入的第一个对象小于、等于还是大于作为参数传入的第二个对象而返回。
预期的对象是T
您在声明类时定义的类型。
在compare()
您编写的方法中,您必须将要实现的任何比较方法解析为-1, a 0, or a 1
.
如何获得这些值取决于您如何评估一个T
类型的对象是否小于、等于或大于相同类型的其他对象。
另一方面,Array.sort()
将使用Comparator
as fit 在数组的两个元素之间进行比较,并作为最终结果返回 sorted Array
。
如果我理解您的说明,则array [1,1,1]
出于订购目的的 , 应解释为String "111"
;
因此,在编程方面Comparator
,会有什么比较(与T
)会arrays
的integers
。
并比较两个arrays
的integers
,每个阵列中的元素应被提取并粘在一起形成String
。一旦你拥有两者Strings
,你就可以看到它们如何相互比较。
添加回答
举报