You must Sign In to post a response.
  • Category: Programming

    Index getting invalid in Arraylist in java

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

    I have a program in java and my showing below :

    ArrayList list = new ArrayList();


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

    Output : -2

    Why it will not showing me the index no is 2 ?
    Please give me the reason with your solution.
  • #137253
    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.


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

  • Sign In to post your comments