Integer i = new Integer(1); Object oi = i; System.out.println("oi add is: " + oi);
i ++; Object oii = i; System.out.println("Integer i is: " + i); System.out.println("oii add is: " + oii);
按理说,java的外覆类,只能在初始化时设定其值,不能在产生i后再改变它的值(i++)。 但是像上面代码中表示的那样,其实可以用i++,而且打印出i的值也确实+1了。 我想验证一下,是不是i++的过程中,java默认重新new了一个Integer,并让i指向了这个新的Integer,但是i++前后,i的地址打印不出来,即使向上转型为Object类后,打印出来的还是1 和2,不是地址。 oi add is: 1 Integer i is: 2 oii add is: 2
看一下Integer中的构造方法和hashcode方法: private final int value;
public Integer(int value) { this.value = value; }
public int hashCode() { return value; } 其它类的hashcode方法,例如HashMap中的: public int hashCode() { int h = 0; Iterator<Entry<K,V>> i = entrySet().iterator(); while (i.hasNext()) h += i.next().hashCode(); return h; } Thread类中的hashcode方法: public native int hashCode();