Java基础题你能对几道?(上)

145 阅读2分钟

一、==符的使用

  首先看一段比较有意思的代码

  Integer a = 1000,b=1000;

  Integer c = 100,d=100; public void mRun(final String name){

  new Runnable() {

  public void run() {

  System.out.println(name);

  }

  };

  }

  如果这道题你能得出正确答案,并能了解其中的原理的话。说明你基础还可以。如果你的答案 是 true 和true的话,你的基础就有所欠缺了。

  首先公布下答案, 运行代码,我们会得到 false true。我们知道==比较的是两个对象的引用,这里的abcd都是新建出来的对象,按理说都应该输入false才对。这就是这道题的有趣之处,无论是面试题还是论坛讨论区,这道题的出场率都很高。原理其实很简单,我们去看下Integer.java这个类就了然了。

  public static Integer valueOf(int i) {

  return i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];}

  /**

  * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing

  */

  private static final Integer[] SMALL_VALUES = new Integer[256];

  static {

  for (int i = -128; i < 128; i++) {

  SMALL_VALUES[i + 128] = new Integer(i);

  }}

  当我们声明一个Integer c = 100;的时候。此时会进行自动装箱操作,简单点说,也就是把基本数据类型转换成Integer对象,而转换成Integer对象正是调用的valueOf方法,可以看到,Integer中把-128-127 缓存了下来。官方解释是小的数字使用的频率比较高,所以为了优化性能,把这之间的数缓存了下来。这就是为什么这道题的答案回事false和ture了。当声明的Integer对象的值在-128-127之间的时候,引用的是同一个对象,所以结果是true。

  二、String

  接着看代码

  String s1 = "abc";

  String s2 = "abc";

  String s3 = new String("abc");System.out.println(s1 == s2);

  System.out.println(s1 == s3);