List sortedList = new LinkedList();
sortedList.addAll(Arrays.asList(new String[]{"ant", "bat", "cat", "dog"}));
// Search for the word "cat"
int index = Collections.binarySearch(sortedList, "cat"); // 2
index = Collections.binarySearch(sortedList, "cow"); // -4
A negative return value indicates that the element is not in the list. However, the actual return value can be used to determine where that non-existent element should be inserted in the list if that were desired; see Inserting an Element into a Sorted List.
No comments:
Post a Comment