如何移动在数组列表具体项目的第一项 [英] How to move specific item in array list to the first item

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

问题描述

例如:一个List

A B C D E

A B C D E

由于C,切换到

C A B D E

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);

这个说法是行不通的,因为它的输出CBADE不CABDE,如何解决它?

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.removeAt(index);
url.add(0, itemToMove);

如果这是一个频繁操作的你,和随机存取是相当少见,你可以考虑切换到另一个列表实施如的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天全站免登陆