![](/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.