问题描述
限时送ChatGPT账号..例如:一个列表
A B C D E
给定 C ,切换到
C A B D E
注意数组大小会发生变化,有些项目可能会在运行时删除
Notice that the array size will change, some items may removed in run times
Collections.swap(url, url.indexOf(itemToMove), 0);
此语句不起作用,因为它输出的是 C B A D E 而不是 C A B D E ,如何解决?
This statement is not working because it output C B A D E not C A B D E , how to fix it?
谢谢.
推荐答案
你想要的是 ArrayList
中的一个非常昂贵的操作.它需要将列表开头和 C
位置之间的每个元素向下移动一个.
What you want is a very expensive operation in an ArrayList
. It requires shifting every element between the beginning of the list and the location of C
down by one.
但是,如果您真的想这样做:
However, if you really want to do it:
int index = url.indexOf(itemToMove);
url.remove(index);
url.add(0, itemToMove);
如果这对您来说是一个频繁的操作,而随机访问的频率则较低,您可以考虑切换到另一个 List
实现,例如 LinkedList
.如果您非常关心元素的顺序,您还应该考虑列表是否是正确的数据结构.
If this is a frequent operation for you, and random access is rather less frequent, you might consider switching to another List
implementation such as LinkedList
. You should also consider whether a list is the right data structure at all if you're so concerned about the order of elements.
这篇关于如何将数组列表中的特定项移动到第一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论