2017-05-17 20 views
-2

我正面臨着如何按幾列排列2維數組的問題。 也許我不應該使用數組。我想知道你的意見,如果有一個優雅的方式來做到這一點。Android Studio - 按3個不同列排列2維數組

我具有文件 「example.txt中」 用下面的行:

1 | A | C |事

2 | A | V |的東西

2 | B | C |東西

3 | B | C |事

3 | A | C |事

3 | A | V |舒美特興

3 | B | V |的東西

4 | A | C |事

,我可以很容易地提取出來並存儲在陣列實施例[] []英寸

下面你可以找到的代碼的部分從文件中讀取:

公共類ActivityExample延伸活動{

@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

而不是一個數組使用類來建模數據。

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; 
    } 
} 
+0

我還應該將文件的信息直接存儲在其他類型的變量(如值列表)中嗎? 我的意思是,col1是Example [i] [0]的值的列表,col2是Example [i] [1]的值的列表.... –

+0

而不是比較數組,我創建了一個ArrayList ,Col2作爲第一個元素,Col2第二個,Col3第三個元素,然後是第四個列。我使用函數Collections.sort(ExampleLista)對ArrayList進行排序; ],最後我將幾個字段拆分成一個數組[使用函數LineSplit st = new StringTokenizer(ExampleItem,「|」);] –