是否有一个 List 实现(在 Java 中)支持移位插入?

发布于 2024-09-04 11:48:10 字数 177 浏览 2 评论 0原文

假设我有一个包含元素

4,7,9,17,24

的列表,我想插入 11 但保持它们有序。 所以我想做一些类似

list.add(3, 11) 的事情,并获得以下列表:

4,7,9,11,17,24

,但如果我这样做,我会将 17 替换为 11。 你能帮忙吗?

Suppose I have a List with the elements

4,7,9,17,24

and I want to insert 11 but to keep them ordered.
So I'd like to do something like

list.add(3, 11), and to get the following list:

4,7,9,11,17,24

but if I do that I get the 17 replaced by 11.
Can you help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

轮廓§ 2024-09-11 11:48:11

如果您需要有序列表,为什么不使用类似 的内容树集。它将使用对象的自然排序,或者您可以传入您自己的比较器。

If you are needing an ordered list why not use something like TreeSet. It will use the natural ordering ordering of the Objects or you can pass in your own comparator.

寻梦旅人 2024-09-11 11:48:11

java.util.List 接口的 add 方法指定应插入(而不是替换)对象。所以奇怪的是它没有被插入到你的程序中。

如果您可以发布导致问题的特定代码,这将会有所帮助

The add method of java.util.List interface specifies that the object should be inserted (not replaced). So it is curious that in your program it does not get inserted.

It would help if you could post your specific code that's causing the problem

生死何惧 2024-09-11 11:48:11

如果列表很小,您可以简单地添加到列表末尾,然后调用list.sort()

If the lists are small, you can simply add to the end of the list and then call list.sort()

堇色安年 2024-09-11 11:48:10

add(int index, E element) 方法应该做你想要的。 javadoc 是这样说的:

在此列表中的指定位置插入指定元素(可选操作)。将当前位于该位置的元素(如果有)和任何后续元素向右移动(为其索引加一)。

如果没有,则您正在使用有缺陷的自定义 List 实现...或者您的应用程序没有执行您认为它正在执行的操作。 (也许您使用了 list.set(3, 11)) ...)

The add(int index, E element) method should do what you want. The javadoc says this:

Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

If it does not, you are using a buggy custom List implementation ... or your application is not doing what you think it is doing. (Perhaps you used list.set(3, 11)) ...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文