我目前正在为java专家的个人资料写一个面试问题。下面是:
考虑到这一守则:
清单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);
}
};
}然后用以下cmd行编译此代码
清单2
javac com/example/Searching.java并使用以下命令行运行
清单3
java com/example/Searching 128问题A:
执行清单3会产生以下结果:
index of 128 is:-8你能解释一下这个输出吗?
问题B:
考虑到这一点
java com/example/Searching 32输出是
index of 32 is:5你能解释一下这个输出吗?
问题C:
假设您有一个JRE1.6、一个shell和一个文本编辑器。您将更改为清单1和/或清单2和/或清单3以生成此输出:
index of 128 is:7备注:你改变的越少,它就越好。
我的问题是:
发布于 2013-02-02 11:11:10
作为面试问题,我会使问题变得更简单。我发现,在面试中,如果不给出提示,就很难解决这类问题。经过几个他们无法回答的问题后,受访者可以放弃这些并不总是有效率的问题。
你能解释一下这个输出吗?
在使用i == j的代码中存在一个错误,它对A&B的影响不同。在一种情况下,排序假定值小于128,在第二种情况下,它与32匹配,因为这是缓存的。
如果您尝试类似于-XX:+AggressiveOpts`或其他选项来增加Integer缓存大小,那么在每种情况下都会匹配。
您将更改为清单1
将i == j ? 0 : -1更改为i > j ? -1 : 0
当然,使用Integer.compare()会出现一些问题;)
如何改进
根据程序的目的,我将使用
int count = 0;
for(int n = Integer.parseInt(args[0]); n != 0; n >>>= 1)
count++;
System.out.println(count);发布于 2013-02-02 11:42:55
答复C:
public class Searching {
public static void main(String[] args) {
int input = Integer.parseInt(args[0]);
int[] values = {1, 2, 4, 8, 16, 32, 64, 128};
System.out.println("index of " + input + " is:" + Arrays.binarySearch(values, input));
}
}因为专家不会让代码像现在这样糟糕。
如何改进面试问题?
或者看看此页。
发布于 2013-02-02 14:11:43
我只想用这个问题来解释我的期望:
问题A:
==和equals的区别)问题B:
问题C:
此外,它还为回答问题B提供了线索。
(例如,在命令行中添加一个系统属性是我期望的答案:java.lang.Integer.IntegerCache.high)。
https://stackoverflow.com/questions/14661188
复制相似问题