Sandesh Sandesh - 3 months ago 10
Java Question

Index not showing properly in Arraylist

I have write a program in

java
of
Arraylist
and my code is showing below:

ArrayList list = new ArrayList();

list.add("aap");
list.add("Janam");
list.add("aaa");
list.add("atm");

int i = Collections.binarySearch(list,"aaa");
System.out.println(i);


It is showing me index no -2.I think it will show me 2.

but in case if I write
list.add("vinit");
in place of
list.add("aaa");

Then I will get the correct and index no 2.

So I can't understand the issue with string "aaa".

Answer

I can get exactly what I want by using list.sort() before Collections.binarySearch(list,"aaa");

Comments