这显然不是我的作品,只是一个例子。 我已经使用 Comparable、compareTo、compare、Collections、sort 等工作了两个多小时。 这不涉及对附加的字符串进行排序,但第一个数字应该与它们各自的单词保持一致。 ArrayList 必须保持完整,但我已经用尽了据我所知的所有其他可能性。
6 Worda
8 Wordb
7 Wordc
20 Wordd
2 Worde
5 Wordf
1 Wordg
10 Wordh
1 Wordi
2 Wordj
新的 ArrayList 类似于:
1 Wordi
1 Wordg
2 Wordj
2 Worde
5 Wordf
6 Worda
8 Wordb
7 Wordc
10 Wordh
20 Wordd
最佳答案
- 创建一个类,其中包含字段来保存每行的信息(这里是一个 int 和一个 String),
- 使类与其自身具有可比性。例如,如果该类名为 MyClass,则让它实现
Comparable<MyClass>
- 给它一个像样的
compareTo(...)
方法 - 在此方法中,您应首先按数字字段排序,如果数字不相等则返回一个值。
- 然后是第二个字符串(如果两个数字相等)。
你说,
This is obviously not my work, but an example of it...
如果您需要更具体的帮助,请考虑发布您的实际代码及其应该保存的实际数据。
<小时/>编辑您发布的内容:
public int compareTo(Team o) {
if (this.apps >= o.apps) {
return this.apps;
} else {
return o.apps;
}
}
如果可以的话请解释一下。
<小时/>例如
// assuming Team has an int field, score and a String field, name
public int compareTo(Team o) {
if (Integer.compare(score, o.score) != 0) {
// the scores are not the same, so return the comparison
return Integer.compare(score, o.score)
} else {
// the scores are the same, so compare the Strings:
return name.compareTo(o.name);
}
}
关于java - 我应该如何按 ArrayList 中包含的一些整数对它进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22427843/