如何对多个不同类型的数组(int 和 String)进行排序

How to sort multiple arrays of different types (int and String)

所以我从一个文本文件中逐行读取一些信息,我基本上将它保存在内存中到不同类型的数组(字符串和整数)。我总共有 2 个字符串数组和 6 个整数数组。

我想按字母顺序对数组 (String) 中的 1 个进行排序,并根据该排序对保存的位置中的其他字符串和整数数组进行排序。

文本文件示例:B,美国,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,它表示您拥有的单个 'entry' 数据类型的组合,并使其成为 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.
     }
}

然后您需要做的就是将这些添加到 Listsort 中。


但是,如果您打算坚持使用基于数组的实现,那么您将需要提供某种形式的方法来识别您排序的数组中哪些索引发生了变化(以及它们从什么变化到什么变化) ),然后将这些更改镜像到其他阵列。

无需为您编写代码,这里是如何仅使用数组实现此目的的简单实现:

  • 在对数组进行排序之前复制一份,以便跟踪索引移动到的位置。
  • 创建另一个 int 数组,长度与该数组相同。
  • 对数组进行排序。
  • 迭代原始元素,并为每个元素迭代排序后的元素以找到新索引。
  • 将此新索引存储在您的 int 数组中(在表示未修改索引的位置)。
  • 使用此 'sorting/index array' 更改您需要根据第一个排序的所有其他数组的索引。