Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Collections

Narsingh Rao
Greenhorn
Posts: 5
Hi

This is my first post in this forum.

Source:Ethumare

import java.util.*;
public class TestClass
{
static String[] sa = { "a", "aa", "aaa", "aaaa"};
static
{
Arrays.sort(sa);
}
public static void main(String[] args)
{
String search = "";
if(args.length != 0) search = args[0];
System.out.println(Arrays.binarySearch(sa, search));
}
}

Here the search is applied on "".O/p should be -1.I have tried i am getting -1.

But the source is saying

Any number from -5 to 3;

Thanks

[ May 30, 2007: Message edited by: Narsingh Rao ]
[ May 30, 2007: Message edited by: Narsingh Rao ]

Zhao zhenhua
Ranch Hand
Posts: 37
Here the search is applied on "".

The default value of search is "".So the output is -1.

But i don't understand what your means of:
But the source is saying

Any number from -5 to 3;

krishna bulusu
Ranch Hand
Posts: 185
I am getting -1 with ""!!!

Narsingh Rao
Greenhorn
Posts: 5
Hi

1)Any number from -5 to 5.
2)Any number from -5 to 5 except -1
3)Any number from -5 to 3.
4)Any number from -5 to 3 except -1.
5)One of a, aa, aaa, or aaaa.
6)One of a, aa, aaa, aaaa, or null.

These are options of that question

They are saying the correct option is 3.

Sheriff
Posts: 14691
16
- If the elements was found, you would get an index between 0 and 3 (because there are only 4 elements in the array)
- If the element was not found, you would get a negative number.
- According to the API, the negative is : (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the list.
- So the biggest index were the element can be inserted is 4 (at the tail). So the returned value is : (-(4) -1) = -5

I have tried but i am getting 0.

I don't understand that. Can you show us your command line ?

Narsingh Rao
Greenhorn
Posts: 5
Hi

Thanks

Satou

I have updated that post .Sorry for the mistake.

Thanks.

Ranch Hand
Posts: 130
Hi Narasingh,
Welcome to javaranch. I agree with satou in this.

If we have got the answer -1 in the list,then that whould have been the aswer of this question.

As that is not the case, i alternate answer is 3.

Good Luck.

Barry Gaunt
Ranch Hand
Posts: 7729
Hi Narasingh,
Welcome to javaranch. I agree with satou in this.

If we have got the answer -1 in the list,then that whould have been the aswer of this question.

As that is not the case, i alternate answer is 3.

Good Luck.

If that is the logic of this question, then it is not testing our knowledge of the Java Collections.binarySearch method. If the question is about the possible results of the binarySearch method for a general input, then it is correct. As it stands we do not know the exact question as asked by the mock exam.