我有2个ArryList:一个Integers和一个Strings。
ArrayList<String> stars = new ArrayList<>();
ArrayList<Integer> index = new ArrayList<>();
index.add(1);
index.add(2);
index.add(3);
index.add(4);
index.add(5);
index.add(6);
stars.add("g");
stars.add("c");
stars.add("a");
stars.add("l");
stars.add("b");
stars.add("q");
我需要重新排列ArryList的值,以便stars.get(index.get(i))将按字母顺序给出stars数组
我输入了以下代码:
for (int x = 0; x < stars.size(); x++) {
for (int y = x+1; y < stars.size(); y++) {
if (stars.get(x).compareTo(stars.get(y)) > 0 ) {
int temp = index.get(x);
index.set(x, index.get(y));
index.set(y, temp);
}
}
}
但是我一直得到这个输出:
[4 2 0 1 3 5]
用于索引数组
代替:
[2 4 1 0 3 5]
谁能帮我找到我做错了什么?
答案 0 :(得分:1)
您只是交换索引列表中位置x和y的元素,还必须交换星号列表中的值
for (int x = 0; x < stars.size(); x++) {
for (int y = x + 1; y < stars.size(); y++) {
if (stars.get(x).compareTo(stars.get(y)) >= 0 ) {
int temp = index.get(x);
index.set(x, index.get(y));
index.set(y, temp);
String strTmp = stars.get(x);
stars.set(x, stars.get(y));
stars.set(y, strTmp);
}
}
}
编辑:如果您无法更改星标列表,则可以使用此代码
for (int x = 0; x < stars.size(); x++) {
for (int y = x + 1; y < stars.size(); y++) {
if (stars.get(index.get(x) - 1).compareTo(stars.get(index.get(y) - 1)) >= 0 ) {
int temp = index.get(x);
index.set(x, index.get(y));
index.set(y, temp);
}
}
}
for (int i = 0; i < index.size(); i++) {
System.out.print(stars.get(index.get(i) - 1) + " ");
}
这给出结果
a b c g l q
答案 1 :(得分:1)
您正在对索引进行排序,但不使用它们来获取要比较的值。更改代码以使用索引值获取stars值:
for (int x = 0; x < stars.size(); x++) {
for (int y = x+1; y < stars.size(); y++) {
if (stars.get(index.get(x)-1).compareTo(stars.get(index.get(y)-1)) > 0 ) {
int temp = index.get(x);
index.set(x, index.get(y));
index.set(y, temp);
}
}
}
注意:-1的完成是因为您要从1到6而不是0到5填充索引数组。这将得到结果[3 5 2 1 4 6]。如果您的预期答案是[2 4 1 0 3 5],请从提取中删除-1,然后使用0到5填充索引数组:
index.add(0);
index.add(1);
index.add(2);
index.add(3);
index.add(4);
index.add(5);
for (int x = 0; x < stars.size(); x++) {
for (int y = x+1; y < stars.size(); y++) {
if (stars.get(index.get(x)).compareTo(stars.get(index.get(y)) > 0 ) {
int temp = index.get(x);
index.set(x, index.get(y));
index.set(y, temp);
}
}
}
答案 2 :(得分:1)
真的不知道该怎么办才能得到:
[2 4 1 0 3 5]
但是,如果您将这些值放在排序后的地图中:
Map<String, Integer> map = new TreeMap<>();
map.put("g", 1);
map.put("c", 2);
map.put("a", 3);
map.put("l", 4);
map.put("b", 5);
map.put("q", 6);
System.out.println(map.values());
您将得到以下结果:
[3、5、2、1、4、6]
答案 3 :(得分:0)
如果您已经拥有stars
列表,则可以执行以下操作:
Collection<Integer> values = new TreeMap<String, Integer>() {{
stars.forEach(key -> put(key, size()));
}}.values();
这是怎么回事?
TreeMap
,这是按键顺序排序的映射。{{ }}
是地图的匿名初始化程序。stars
的每个条目,请添加具有适当索引的键({{1}从size()
开始,每个put()
都会递增)。结果:
0
但是假设,您也需要保留[2, 4, 1, 0, 3, 5]
列表,并且要自己实现排序,那么就需要交换index
和 {{ 1}}:
stars
这将导致:
index
似乎您想拥有一个从0开始的索引(但是认真的:为什么用for (int x = 0; x < stars.size(); x++) {
for (int y = x + 1; y < stars.size(); y++) {
if (stars.get(x).compareTo(stars.get(y)) > 0) {
Collections.swap(stars, x, y);
Collections.swap(index, x, y);
}
}
}
初始化索引列表?),那么您需要减去每个索引值的[3, 5, 2, 1, 4, 6]
:
1