I'm currently writing an interview question for a java expert profile. Here it is:
Considering this code :
listing 1
package com.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Searching {
public static void main(String[] args) {
int input = Integer.valueOf(args[0]);
String[] strings = {"1", "2", "4", "8", "16", "32", "64", "128"};
List<Integer> integers = new ArrayList<Integer>();
for (String s : strings) {
integers.add(Integer.valueOf(s));
}
System.out.println("index of "+input+" is:"+Collections.binarySearch(integers, input, cmp));
}
static Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer i, Integer j) {
return i < j ? -1 : (i == j ? 0 : 1);
}
};
}
This code is then compiled with this cmd line
listing 2
javac com/example/Searching.java
and run with this command line
listing 3
java com/example/Searching 128
QUESTION A:
Executing listing 3 produce:
index of 128 is:-8
Can you explain this output ?
QUESTION B:
Considering this
java com/example/Searching 32
output is
index of 32 is:5
Can you explain this output ?
QUESTION C:
Assuming you have a JRE 1.6, a shell, and a text editor. What would you change to listing 1 and/or listing 2 and/or listing 3 to produce this output:
index of 128 is:7
remark: the less you change, the better it is.
My questions are :
- what would be your answer to those questions ?
- how to improve it ?