@Atrakeur
"sorting the entire list each time a new item is added is ineffective"
This is true, but if you want the list to always be in sorted state, this is really the only option.
"The best way is to insert the element directly where it should be (in its correct position). To do this, you can encode all the positions to find where this number belongs."
This is exactly what the sample code does.
"or use Collections.binarySearch so that this optimized search algorithm does the job for you"
Binary search is effective, but only for random access lists. That way you can use a list of arrays instead of a linked list, but then you have to deal with copies of memory as the list grows. You will also consume more memory than you need if the capacity of the list is higher than the actual number of elements (which is quite common).
So, what data structure / approach will greatly depend on your storage and access requirements.
[edit] In fact, there is one problem with the sample code: this leads to multiple scrolling through the list.
int i = 0; while (llist.get(i) < val) { i++; } llist.add(i, val);
The get (i) call will go through once to go to the i-th position. Then the call to add (i, val) crosses it again. So it will be very slow.
A better approach would be to use ListIterator to move around the list and perform the insertion. This interface defines the add () method, which you can use to insert an element at its current position.
source share