Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of newly added item in a list?

I want to get the index of a newly added element into an arraylist. e.g.

List listA = new ArrayList();

// Lots of code adding and removing things from `listA`, imagine `listA` now 
// contains approx 10,000 records

listA.add("element 0");

How do I find out the index of the newly added item?

I think that perhaps, I need a different data structure, but cannot think of what to use.

like image 228
Matthew Smith Avatar asked Aug 26 '14 13:08

Matthew Smith


People also ask

How do you find the index of an item in a list in Python?

To find the index of a list element in Python, use the built-in index() method. To find the index of a character in a string, use the index() method on the string. This is the quick answer.

What is the index of the first item in a list?

Index in a list starts with 0. This essentially means that the first element in the list has an index of 0 and not 1 and subsequently the second element has an index of 1. This concept holds true for most programming languages.

How do you get the index of an item in a list in Java?

The standard solution to find the index of an element in a List is using the indexOf() method. It returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.


1 Answers

The first element added to the list would have index 0.
The last element added would have the index listA.size()-1.
However, you should note that if you remove elements from the list, some of the indices (indices of elements that had higher index than the removed element) would change. For example, if you remove the n'th element, the former (n+1)'th element would become the n'th element.

Thanks talex for the comment. I forgot about indexOf(), which returns the index of the supplied element (if that element is found in the list). However, this requires linear search time.

If you wish to treat the indices of the list as keys to find the values stored in the list, you might be better off using a HashMap<Integer,String>.

like image 127
Eran Avatar answered Sep 28 '22 04:09

Eran