我有一个多维字符串数组处理[100][2],如下所示:
Y B C D B B C F EE Y
F D X YE G
我想按第一列字母排序,使最终结果看起来如下:
B B C C DE Y
E G
F E F D Y BX Y我试过使用下面的代码,但这并不奏效:
Arrays.sort(process, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
我得到的输出是:
B B C C D E Y
F E Y BE G
F D X Y下面的单元测试演示了一个工作的Comparator
实现。测试也打印出结果。
import java.util.Arrays;
import java.util.Comparator;
import junit.framework.TestCase;
public class ArrayTest extends TestCase {
public class Sorter implements Comparator {
public int compare(Object o1, Object o2){
String[] arrayOne = (String[])o1;
String[] arrayTwo = (String[])o2;
return arrayOne[0].compareTo(arrayTwo[0]);
}
}
public void testSort() {
String[][] testData = {
{"Y", "B"},
{"C", "D"},
{"A", "B"},
{"B", "C"},
{"F", "E"},
{"E", "Y"},
};
Arrays.sort(testData, new Sorter());
String[][] expectedOutput = {
{"A", "B"},
{"B", "C"},
{"C", "D"},
{"E", "Y"},
{"F", "E"},
{"Y", "B"},
};
for(int i = 0; i < testData.length; ++i) {
System.out.println(testData[i][0] + " " + testData[i][1]);
assertEquals(expectedOutput[i][0], testData[i][0]);
assertEquals(expectedOutput[i][1], testData[i][1]);
}
}
}
这段代码(相同的比较器)按预期工作:
String[][] arr = {{"B","L"},{"C","M"},{"Z","N"}};
Arrays.sort(arr, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final String time1 = entry1[0];
final String time2 = entry2[0];
return time1.compareTo(time2);
}
});
你的问题一定在别处
最好将这两个字符放在每行的同一元素中。然后,当需要分隔字符时,使用
String firstCharacter = myString.charAt(0);
String secondCharacter = myString.charAt(1);
你可以对你的一维数组进行排序