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 ?
As an interview question, I would make the problem simpler. I have found that in interviews it can be much harder to solve these sort of problems without allot of hints. After a couple of questions they can’t answer, interviewees can give up which isn’t always productive.
There is a bug in the code with
i == jwhich impact A & B differently. In one case the sort assumes the value is less than 128 and in the second it matches 32 because this is cached.If you try something like -XX:+AggressiveOpts` or another option to increase the Integer cache size it would match in each case.
Change
i == j ? 0 : -1toi > j ? -1 : 0Of course using Integer.compare() would some the problem 😉
Depending on the purpose of the program, I would use