Reputation: 176
I have a ArrayList
with sorted Integer
numbers. I need to insert an element into the list, but i need to know at what location insertion should happen to maintain the ordering.
If I just add it and use Collections.sort()
then I won't not be able to find the location of the inserted element.
Upvotes: 0
Views: 271
Reputation: 61
System.out.println(list.indexOf(10));
--- ull see answer as 5 . means at 5+1(6th position) the value is inserted .it is already said by Juned Ahsan
Upvotes: 1
Reputation: 34424
From javadocs
add(E e) Appends the specified element to the end of this list.
So to find index you can do size-1
at the time of addition
Upvotes: 1
Reputation: 68715
Use ArrayList indexOf
public int indexOf(Object o)
returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element
Upvotes: 6