在面试中,我遇到了一个面试题,要求我实现一个功能,使得在满足某个判断条件时,程序能够打印输出 “Success”。请问我应该如何处理这个问题?
public static void main(String[] args) throws Exception {
Integer a = 1;
if (a.equals(1) && a.equals(2) && a.equals(3)) {
System.out.println("Success");
} else {
System.out.println("Error");
}
}
// 输出结果:Error
看完我就懵了,于是就在网上搜索,查询到了解决方案。主要考察就是你对Integer缓存和反射机制的了解。
private static void test2() throws NoSuchFieldException, IllegalAccessException {
Class cache = Integer.class.getDeclaredClasses()[0];
Field c = cache.getDeclaredField("cache");
c.setAccessible(true);
Integer[] array = (Integer[]) c.get(cache);
array[130] = array[129];
array[131] = array[129];
}
// 输出结果:Success
Integer会将-127~128加入到缓存数组中,我们通过反射把1的缓存赋值给2和3,最终实现等式成立。
打赏



当前共有 0 条评论