如何将数组列表中的特定项移动到第一项

编程入门 行业动态 更新时间:2024-10-27 02:23:44
本文介绍了如何将数组列表中的特定项移动到第一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-16 11:50:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/885823.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   到第   如何将   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!