我正在尝试对 java 中的二维字符串数组的每一行进行排序。
示例:
例如,如果数组包含:
ZCD
BFE
DZA
我希望它排序为:
CDZ
BEF
ADZ
代码:
private String[] commonCollections;
private int comparisons = 0;
public Comparable[] findCommonElements(Comparable[][] collections){
for(int i = 0; i < collections.length; i++){
Arrays.sort(collections[i]);
}
for(int i = 0; i <collections[0].length; i++){
System.out.print(collections[0][i] + "\n");
}
return commonCollections;
}
谢谢。对于上面的代码,由于某种原因它没有排序。
最佳答案
你的排序看起来不错。您的打印方式是问题所在。
这是你想要的吗?
public class Main {
public static Comparable[][] findCommonElements(Comparable[][] collections){
for(int i = 0; i < collections.length; i++){
Arrays.sort(collections[i]);
}
return collections;
}
public static void main(String[] args) {
Character [][]input= {{'Z','C','D'},{'B','F','E'},{'D','Z','A' }};
Comparable[][] output = findCommonElements(input);
for(int i = 0; i <output.length; i++){
System.out.print(Arrays.toString(output[i]) + "\n");
}
}
}
产生以下输出:
[C、D、Z] [B、E、F] [A、D、Z]
关于java - 如何使用 Arrays.sort 对 java 中的二维字符串数组中的每一行进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39549852/