Ask Experts » Computers » Programming »

Index getting invalid in Arraylist in java


Date: 03 Jul 2016   Posted By: Sandesh kanungo     Group: Computers    Category: Programming   

I have a program in java and my 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);



Output : -2

Why it will not showing me the index no is 2 ?
Please give me the reason with your solution.


Please check the java code, Java code not showing me the index no


Author: Chaitan    10 Jul 2016      Member Level: Silver     Points : 3  (Rs 3)    Voting Score: 0

The binarySearch method of the class Collections assumes that the list passed as argument to it, in this case 'list', is already sorted. If the list passed to the method is not sorted then this may result in undefined behaviour. For proper usage of the binarySearch function one should always sort the list before calling it.

"Collections.sort(list);"

Use the above code fragment in your program before you call the binarySearch method. Hopefully this clears your doubt.





Post Answer



You must Sign In to post a response.


Post Answer        





Related Questions
  • Return to Question Index
  • Ask Question to Experts


  • Awards & Gifts
    Top Contributors
    TodayLast 7 Daysmore...

     
    ISC Technologies, Kochi - India. © All Rights Reserved.