是否有一个 List 实现(在 Java 中)支持移位插入?
假设我有一个包含元素
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您需要有序列表,为什么不使用类似 的内容树集。它将使用对象的自然排序,或者您可以传入您自己的比较器。
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.
浏览一下集合文档,看看是否可以找到满足您需求的文档:
http://java.sun.com/javase/7/docs/api/java/util/LinkedList.html
http://java.sun.com/docs/books/tutorial/collections/implementations/list.html
Have a poke around the Collections documentation, see if you can find one to suit your needs:
http://java.sun.com/javase/7/docs/api/java/util/LinkedList.html
http://java.sun.com/docs/books/tutorial/collections/implementations/list.html
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
如果列表很小,您可以简单地添加到列表末尾,然后调用
list.sort()
If the lists are small, you can simply add to the end of the list and then call
list.sort()
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: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 usedlist.set(3, 11))
...)