![](/img/trans.png)
[英]Arrays.sort() works different for int[] and String for same input why?
[英]How to sort multiple arrays of different types (int and String)
所以我從一個文本文件中逐行讀取一些信息,我基本上將它保存在內存中到不同類型(字符串和整數)的數組中。 我總共有 2 個 String 數組和 6 個 int 數組。
我想按字母順序對數組(字符串)中的 1 個進行排序,並基於該數組對保存的位置中的其他字符串和整數數組進行排序。
文本文件示例:B,United States,3,1,0,2,2,7
C,英國,3,1,2,0,2,1
A,丹麥,3,3,2,0,2,1
每當我在文本文件中讀取一行時,我提到的那些數組就會被保存。 所以,我在位置 0 有一個 string,string,int,int,int,int,int 用於初學者等等,直到讀取最后一行。
Ps:閱讀文本文件后,我不應該再擁有文本文件,只能使用內存中保存的信息。 (不使用對象)
創建一個表示單個“條目”的數據類型組合的Object
,並使其為該類型implement Comparable
。
public class MyEntry implements Comparable<MyEntry> {
private String theStringToSortOn;
private String theOtherString;
private int theFirstInt;
private int theSecondInt;
// ...
public int compareTo(final MyEntry entry) {
int comparison = String.compare(this.theStringToSortOn, entry.theStringToSortOn);
if (comparison != 0) {
return comparison;
}
// Do some other rudimentary sorting based on the other fields of the class.
}
}
然后您需要做的就是將它們添加到List
並對其sort
。
但是,如果您打算堅持使用基於數組的實現,那么您需要提供某種形式的方法來識別您排序的數組中哪些索引發生了變化(以及它們的變化),然后鏡像那些對其他數組的更改。
在不為您編寫代碼的情況下,這里是如何僅使用數組實現此目的的簡單實現:
int
數組。int
數組中(在表示未修改索引的位置)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.