如何将数组列表中的特定项移动到第一项 [英] How to move specific item in array list to the first item

查看:28
本文介绍了如何将数组列表中的特定项移动到第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:一个列表

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆