Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move specific item in array list to the first item

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.

like image 587
user782104 Avatar asked Nov 25 '13 07:11

user782104


People also ask

How do I move an element to a list first?

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.

How do you swap two items in an ArrayList?

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.

Is ArrayList first in first out?

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.


2 Answers

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.

like image 132
Chris Hayes Avatar answered Sep 30 '22 04:09

Chris Hayes


Do this:

  1. Remove the element from the list: ArraylistObj.remove(object);
  2. Add the element back to the list at specific position: ArrayListObj.add(position, Object);

As per your code use this :

url.remove("C"); url.add(0,"C"); 
like image 26
Venkata Krishna Avatar answered Sep 30 '22 03:09

Venkata Krishna