int与Integer

  1. int与Integer比较,会经历自动拆箱的过程
  2. 得到一个Integer由两种方式:一种是例如new Integer(123);一种是例如Integer a=123,会调用Integer.valueOf(123)方法。
  3. new出来的对象都是在堆上分配内存,Integer.valueOf()方法源码如下
    /**
     * Returns an {@code Integer} instance representing the specified
     * {@code int} value.  If a new {@code Integer} instance is not
     * required, this method should generally be used in preference to
     * the constructor {@link #Integer(int)}, as this method is likely
     * to yield significantly better space and time performance by
     * caching frequently requested values.
     *
     * This method will always cache values in the range -128 to 127,
     * inclusive, and may cache other values outside of this range.
     *
     * @param  i an {@code int} value.
     * @return an {@code Integer} instance representing {@code i}.
     * @since  1.5
     */
    public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

  1. Object类有13个方法


    int与Integer_第1张图片
    Object类的13个方法

    其中hashCode(),equals(Object),clone(),toString(),finalize()方法不是final的,可以由子类重写。其中equals(Object),toString(),finalize()方法不是native的,源码如下。

    public boolean equals(Object obj) {
        return (this == obj);
    }
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    protected void finalize() throws Throwable { }
  1. Integer类重写了Object类的方法,包括toString(),hashCode(),equals(Object)。
    public String toString() {
        return toString(value);
    }
    public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(buf, true);
    }
    public int hashCode() {
        return Integer.hashCode(value);
    }
    public static int hashCode(int value) {
        return value;
    }
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

而且Integer类implements Comparable,实现了compareTo(Integer)和compare(int,int)方法

    public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }
    public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }

有以下测试代码

Integer a=new Integer(1);
Integer b=new Integer(1);
System.out.println(a==b);//false
System.out.println(a.equals(b));//true
System.out.println(a.hashCode()==b.hashCode());//true
System.out.println(a.compareTo(b)==0);//true

你可能感兴趣的:(int与Integer)