Sravan2023
Sravan2023

Reputation: 176

Find insertion location in a sorted ArrayList

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

Answers (3)

Luckyman Nevermore
Luckyman Nevermore

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

M Sach
M Sach

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

Juned Ahsan
Juned Ahsan

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

Related Questions