Boolean Boolean - 1 year ago 153
Java Question

Swap elements in LinkedList

I want to maintain order of the elements being added in a list. So, I used a

in Java.

Now I want to be able to swap two elements in the linked list. First of all, I cannot find an
. Also, there is no way to add element at a specified position.

Answer Source

There is a Collections.swap(List<?> list, int i, int j) that you can use to swap two elements of a List<?>. There's also LinkedList.get(int index) and LinkedList.add(int index, E element) (both are methods specified by interface List). All of these operations will be O(N) since a LinkedList does not implements RandomAccess.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download