gpt4 book ai didi

java - 根据 int 数组的第一个和第二个元素对 int 数组的数组列表进行排序

转载 作者:行者123 更新时间:2023-12-01 09:32:04 25 4
gpt4 key购买 nike

ArrayList<int[]> segment = new Arraylist<int[]>();
segment.add(new int[]{2,3,1});
segment.add(new int[]{2,1,1});
segment.add(new int[]{1,1,1});
segment.add(new int[]{2,4,1});
segment.add(new int[]{3,3,1});

我想要做的是根据每个数组的第一个元素对这个 ArrayList 进行排序,如果元素相同,则根据一个/多个数组的第二个元素进行排序

例如上面的代码行应该修改为,(1,1,1)(2,1,1)(2,3,1)(2,4,1)(3,3,1)

这就是我到目前为止解决这个问题的方法,

    public static void SortSegment(ArrayList<int[]> segment){
Collections.sort(segment, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return (a[0] - b[0]);
}
});
}

这段代码根据每个 int 数组的第一个元素对 int 数组的 arraylist 进行排序。我如何修改它以适用于第一个元素相同的情况,以便考虑第二个元素?

谢谢。

最佳答案

试试这个

if(a[0] - b[0]==0) //Like the first row of the matrix if so, we proceed to the next to know which is lower

代码完成

Collections.sort(segment, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if(a[0] - b[0]==0) //if equals
{
return a[1]-b[1];//recompare
}
else
return a[0]-b[0];
}
});

关于java - 根据 int 数组的第一个和第二个元素对 int 数组的数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39323208/

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