For example : A list
A B C D E
Given C , Switch to
C A B D E
Notice that the array size will change, some items may removed in run times
Collections.swap(url, url.indexOf(itemToMove), 0);
This statement is not working because it output C B A D E not C A B D E , how to fix it?
Thanks.
Get the position (index) of the item using the indexOf() method of the ArrayList class. Remove it using the remove() method of the ArrayList class. Finally, add it to the index 0 using the add() method of the ArrayList class.
In order to swap elements of ArrayList with Java collections, we need to use the Collections. swap() method. It swaps the elements at the specified positions in the list.
Arraylist will hold the last element added at the end of the list. So it keeps the order of insertion. But it's a random access container, it doesn't really have a sense of first in first out. As a side note, just based on the way that ArrayList works internally, it wouldn't be a good idea to use it as a FIFO queue.
What you want is a very expensive operation in an ArrayList
. It requires shifting every element between the beginning of the list and the location of C
down by one.
However, if you really want to do it:
int index = url.indexOf(itemToMove); url.remove(index); url.add(0, itemToMove);
If this is a frequent operation for you, and random access is rather less frequent, you might consider switching to another List
implementation such as LinkedList
. You should also consider whether a list is the right data structure at all if you're so concerned about the order of elements.
Do this:
ArraylistObj.remove(object);
ArrayListObj.add(position, Object);
As per your code use this :
url.remove("C"); url.add(0,"C");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With