我遇到了如何按几列订购2维数组的问题。 也许我不应该使用数组。我想知道你的意见,如果有一个优雅的方式去做。
我的文件“Example.txt”包含以下行:
1个| A | C |事
2 | A | V | Something
2 | B | C | Something
3 | B | C | Something
3 | A | C | Something
3 | A | V | Something
3 | B | V | Something
4 | A | C | Something
我可以轻松地提取它们并存储在数组Example [] []。
中您可以在下面找到要从文件中读取的部分代码:
公共类ActivityExample扩展了Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
int Max_Linhas=100;
int Max_Colunas=10;
int Linha=0;
String[][] Example = new String[Max_Linhas][Max_Colunas];
try {
InputStream inputStream = openFileInput("Example.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
while ( (receiveString = bufferedReader.readLine()) != null ) {
StringTokenizer st = new StringTokenizer(receiveString, "|");
Example [Linha][0]= st.nextToken();
Example [Linha][1]= st.nextToken();
Example [Linha][2]= st.nextToken();
Example [Linha][3]= st.nextToken();
Linha++;
}
inputStream.close();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Somewhere here I would like to ORDER this array by Column 1, Column 0, column 2 ASCENDING
}
}
我在数组中有[] []值:
[1;一个; C;东西]
[2;一个; V;东西]
[2; B; C;东西]
[3; B; C;东西]
[3;一个; C;东西]
[3;一个; V;东西]
[3; B; V;东西]
[4;一个; C;东西]
我想按第2栏第1栏和第3栏的顺序排序。
最终结果应为:
[1;一个; C;东西]
[2;一个; V;东西]
[3;一个; C;东西]
[3;一个; V;东西]
[4;一个; C;东西]
[2; B; C;东西]
[3; B; C;东西]
[3; B; V;东西]
提前谢谢
答案 0 :(得分:0)
而不是数组使用类来建模数据。
class Model implements Comparable<Model> {
String col1, col2, col3, col4;
@Override
public int compareTo(@NonNull Model o) {
// Assumes fields are not null
int result = col2.compareTo(o.col2);
if(result != 0){
return result;
}
result = col1.compareTo(o.col1);
if(result != 0){
return result;
}
result = col3.compareTo(o.col3);
if(result != 0){
return result;
}
return 0;
}
}