Successfully reported this slideshow.

# 19) Assume that bands is an ArrayList of String objects which contains.docx

Upcoming SlideShare
Array list(1)
×

# 19) Assume that bands is an ArrayList of String objects which contains.docx

19) Assume that bands is an ArrayList of String objects which contains a number of elements in ascending order. Select a statement to complete the code segment below, which invokes the Java library binarySearch method to search for the string \"Beatles\". If the list does not already contain the string, it should be inserted in an appropriate location so that the list remains sorted.
int index = Collections.binarySearch(bands, \"Beatles\");
if (index < 0)
{
__________________________
}
a) bands.add(-1 * index + 1, \"Beatles\");
Solution
Ans: d) bands.add(-1 - index, \"Beatles\");
Explanation:
int index = Collections.binarySearch(bands, \"Beatles\");
Returns:
the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
.

19) Assume that bands is an ArrayList of String objects which contains a number of elements in ascending order. Select a statement to complete the code segment below, which invokes the Java library binarySearch method to search for the string \"Beatles\". If the list does not already contain the string, it should be inserted in an appropriate location so that the list remains sorted.
int index = Collections.binarySearch(bands, \"Beatles\");
if (index < 0)
{
__________________________
}
a) bands.add(-1 * index + 1, \"Beatles\");
Solution
Ans: d) bands.add(-1 - index, \"Beatles\");
Explanation:
int index = Collections.binarySearch(bands, \"Beatles\");
Returns:
the index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size() if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
.