java中如何将一个元素放到ArrayList的顶部
我有一个 ArrayList,我需要对其进行排序,并且我还需要一个特定的默认项位于列表顶部。我可以通过检查数组列表、删除默认项目并将其插入列表顶部来自己完成此操作。
基本上,列表应该在顶部有一个默认值,其余值按排序顺序排列。是否有任何现有的 API 方法可以执行此操作?
I have an ArrayList
which I need to sort and also I need a specific default item to be on top of the list. I can do that myself by checking the array list, deleting the default item, and inserting it at the top of the list.
Basically the list should have a default value on top and remaining values in sorted order. Is there is any existing API method that does this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只是编写一个方法来执行您所描述的操作...类似于:
您还可以使用比较器(尽管它不太明显),它总是将默认项目与任何比较中的最低项进行比较,并将自然项与默认项进行比较。其余项目的比较。为此,您可以调用 Collections.sort(List, Comparator);
这是此类比较器的一些代码......再次。我不太喜欢它,因为它并不明显......但我认为这是一个合理的解决方案:
I'd just write a method that did what you describe... something like:
You could also make use of a Comparator (it would be less obvious though) where it always compares the default item as the lowest in any comparison and the natural comparison for the rest of the items. For that you would call Collections.sort(List, Comparator);
Here is some code for such a Comparator... again. I don't really like it because it isn't obvious... but it is a reasonable solution I guess:
在此列表中的指定位置 (
index
) 插入指定元素 (E
)。将当前位于该位置的元素(如果有)和任何后续元素向右移动(将其索引加一)。如果需要将元素放在列表顶部,可以将
index
设置为 0。Inserts the specified element (
E
) at the specified position (index
) in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).index
can be set to 0 if you need to put the element at top of list.据我所知。
您可能只需要像您所说的那样手动执行一些操作...例如
Not that I'm aware of.
You might just need to do something manually like you said...e.g.