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.
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.
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.
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.
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>
.
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