gpt4 book ai didi

java - 如何使用 `Comparator` 接口(interface)对二维数组进行排序?

转载 作者:行者123 更新时间:2023-12-01 07:10:07 27 4
gpt4 key购买 nike

我需要对以下数组进行排序:

String [][] myArray = {{"John", "3", "10"}, {"Paul", "16","2"}, 
{"Mike","8","20"}, {"Peter","5","0"}};

进入以下数组:

String [][] myArray = {{"John", "3", "10"}, {"Mike","8","20"}, 
{"Paul", "16","2"}, {"Peter","5","0"}};

我有两个类。第一个包含数组,另一个实现 Comparator 接口(interface)。这是 MyArray 类:

public class MyArray {
public static void main(String[] args) {
String [][] myArray = {{"John", "3", "10"}, {"Paul", "16","2"},
{"Mike","8","20"},{"Peter","5","0"}};
ByName byName = new ByName();
Arrays.sort(myArray,byName);
}
}

这是 ByName 类:

  import java.util.Comparator;
public class ByName implements Comparator {
public int compare(Object o1, Object o2) {
String name1 = (String)((MyArray) o1)[0]);
String name2 = (String)((MyArray) o2)[0]);
return (name1>name2) ? 1 : -1;
// Here I am confused, how can I compare it, how can I sort my array
// alphabetically by the first element of each element, i.e. by the names.
}
}

最佳答案

你几乎明白了:而不是 <

return (name1>name2) ? 1 : -1;

使用compareTo() :

String name1 = ((String[])o1)[0];
String name2 = ((String[])o2)[0];
return name1.compareTo(name2);

关于java - 如何使用 `Comparator` 接口(interface)对二维数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16127867/

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