tags:

views:

69

answers:

5

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?

+8  A: 

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

Stephen C
oooooooh, you got it! I'm sorry, I was using set instead of add xD
Manuel
+2  A: 

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

Ash Kim
A: 

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

DVK
That is relatively expensive even if the list is always small.
Stephen C
@Stephen C - depends on usage. For somewhat infrequent inserts it's actually ideal
DVK
+1  A: 

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

byneri
+3  A: 

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.

jschoen
@jschoen - there are two kinds of ordering. A `List` preserves element *insertion* order. An `SortedSet` (like `TreeSet`) orders based on element values. It *looks* like the OP wants the latter kind ... but he *might* want the former kind.
Stephen C
@Stephen You are right about the difference, it seemed to me he was essentially wanting an ordered collection, but was doing it manually (my guess) and was suggesting another route that seemed simpler.
jschoen
Thanks, this is what I needed!
Manuel
Glad I could help.
jschoen