Use*_*920 6 java arrays arraylist multidimensional-array
我有一个arraylist和一个String数组.String数组包含ID,Array List包含与这些ID相关的ID和信息.此ArrayList处于不合需要的顺序.我有一个ID数组的字符串数组,我希望它们在ArrayList中.
半伪码示例:
ArrayList<MyObject> myList = new ArrayList<MyObject>();
for (every username)
{
myList.add(new MyObject(id, username, content, country);
}
String[] ids = new String[myList.size()];
...Ids are added and sorted here...
Run Code Online (Sandbox Code Playgroud)
我现在有一个ID列表,按正确的顺序排列."myList"中的每个Id对应于"ids"字符串数组中的Id.我想根据"ids"字符串数组中相应id的顺序对"myList"进行排序.
如何以这种方式重新排序我的ArrayList?
Eg. if in Array list I have:
1. 123, Bob, test, USA
2. 1234, Vladimir, test, USA
3. 12345, Yoseph, test, USA
and in the String[] I have:
1. 1234
2. 123
3.12345
Run Code Online (Sandbox Code Playgroud)
如何根据字符串数组中的Ids重新排序ArrayList,从而产生:
1. 1234, Vladimir, test, USA
2. 123, Bob, test, USA
3. 12345, Yoseph, test, USA
Run Code Online (Sandbox Code Playgroud)
一种解决方案是迭代ids数组,并在对象中搜索数组中的当前数据id.我们知道它的最终(所需)位置:它是数组中的索引(因为我们希望列表就像数组一样排序),所以我们可以将这个元素移动到列表中的最后位置(我们通过交换它来实现这一点)元素位于我们当前在数组中的位置).
for (int i = ids.length - 1; i > 0; i--) { // Downward for efficiency
final String id = ids[i];
// Big optimization: we don't have to search the full list as the part
// before i is already sorted and object for id can only be on the remaining
for (int j = i; j >= 0; j--) // NOTE: loop starting at i
if (id.equals(myList.get(j).getId()) {
Collections.swap(myList, j, i);
break;
}
}
Run Code Online (Sandbox Code Playgroud)
注意:for循环省略了最后一个元素(i==0),因为如果所有其他元素都在适当位置,则最后一个元素也在(它)的位置.
这比创建比较器和使用排序算法(Collections.sort()例如)更快,因为元素的顺序已经知道(由ids数组定义)和排序算法(无论算法有多聪明)都只能使用[less | equals | greater]比较器返回的信息.
| 归档时间: |
|
| 查看次数: |
1285 次 |
| 最近记录: |