Java-API学习笔记---Integer

2 篇文章 0 订阅
1 篇文章 0 订阅

首先来看Integer类的继承关系,该类继承自Java中的Number类,Number类又继承自Java中的顶层类Object。

Java源码中对该类的注释如下:


 * The <code>Integer</code> class wraps a value of the primitive type
 * <code>int</code> in an object. An object of type
 * <code>Integer</code> contains a single field whose type is
 * <code>int</code>.
 *
 *  <p>
 * 
 * In addition, this class provides several methods for converting an
 * <code>int</code> to a <code>String</code> and a <code>String</code>
 * to an <code>int</code>, as well as other constants and methods
 * useful when dealing with an <code>int</code>.

翻译成中文如下:

Integer 类在对象中包装了一个基本类型 int 的值。Integer 类型的对象包含一个 int 类型的字段。 

此外,该类提供了多个方法,能在 int 类型和 String 类型之间互相转换,还提供了处理 int 类型时非常有用的其他一些常量和方法。

下面来看Integer类的成员变量:

public static final int MIN_VALUE = 0x80000000;

表示了Integer所能表示的最小值。这里有两点需要注意:1.从这个成员变量我们能够看到Java的平台无关性,不像C或C++语言那样,int值的二进制位数是和CPU位数紧密相关的,而Java的这个相关性却是和你下载的JDK包的位数是相关的。2.这个最小值是用16进制补码表示的,而且是有符号的转换为二进制补码就是 1000……(省略号代表28个0)第一位代表了正负,其相应的源码是1111……0(总共31个1,最后一位是0)就是-2 31.

public static final int   MAX_VALUE = 0x7fffffff;
这个同最小值一样,也是16进制补码表示,就是2 31-1

public static final int SIZE = 32;
用来以二进制补码形式表示 int 值的比特位数。如果你下载的是32位的JDK,那么这个就是32了~

public static final Class<Integer>	TYPE = (Class<Integer>) Class.getPrimitiveClass("int");

表示基本类型 intClass 实例。getPrimitiveClass是个native方法,在此不多说。

private final int value;

还有这么一个私有的成员变量,Integer所表示的int值就是在这个变量中保存的了。

***************************************************************************************************

Integer中有两个构造方法:

public Integer(int value)
public Integer(String s)
前者是直接将int类型的值赋给了Inter类中的成员变量alue。后者是调用了 parseInt(s, 10)方法进行转换之后才赋给value的。
***************************************************************************************************

下面来介绍Integer中的toString方法以及类toString方法:

public String toString()
public static String toString(int i)
public static String toBinaryString(int i)
public static String toOctalString(int i)
public static String toHexString(int i)
public static String toString(int i, int radix)

前面两个toString方法是将int值转换为String类型。第一个是直接调用了String.valueOf()方法。第二个则是对int值经过处理之后得到的,其处理源码如下:

    public static String toString(int i) {
        if (i == Integer.MIN_VALUE)
            return "-2147483648";//最小值必须这样处理,否则按照下面处理方法将造成int越界错误
        int size = (i < 0) ? stringSize(-i) + 1 : stringSize(i);
        char[] buf = new char[size];
        getChars(i, size, buf);
        return new String(0, size, buf);
    }

后面几个toString方法我称之为“类toString”,意思就是类似于toString方法,他们同样是将int值转换为String,只不过转换的结果形式不一样罢了,二进制、八进制、十六进制等。了解其内部处理有个方法必须了解,因为这几个方法最终都是调用了这个方法,其如下:

private static String toUnsignedString(int i, int shift) {
	char[] buf = new char[32];
	int charPos = 32;
	int radix = 1 << shift;
	int mask = radix - 1;
	do {
	    buf[--charPos] = digits[i & mask];
	    i >>>= shift;
	} while (i != 0);

	return new String(buf, charPos, (32 - charPos));
    }
其按要求转换的进制数,对int值进行移位之后才进行的String转换。

聪明的同学可能会问了,上面这个方法只能对2的倍数的进制进行转换。对于任意进制转换则无能为力。是啊,于是Java本身又有另一个方法处理这种情况:

public static String toString(int i, int radix) {

        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
	    radix = 10;

	/* Use the faster version */
	if (radix == 10) {
	    return toString(i);
	}

	char buf[] = new char[33];
	boolean negative = (i < 0);
	int charPos = 32;

	if (!negative) {
	    i = -i;
	}

	while (i <= -radix) {
	    buf[charPos--] = digits[-(i % radix)];
	    i = i / radix;
	}
	buf[charPos] = digits[-i];

	if (negative) {
	    buf[--charPos] = '-';
	}

	return new String(buf, charPos, (33 - charPos));
    }

在这个方法中对int值进行了循环取余的操作,之后才能进行String的转换。如果以前没有用过这个方法的童鞋们,你们以前有没有重复制造轮子呢?毕竟这种处理的逻辑还是很绕的~我们后面有需求还是直接使用这个方法得了~~

顺便提及Integer继承Object类并实现其中的几个方法:

    public boolean equals(Object obj) {
	if (obj instanceof Integer) {//这是一个常识,当我们在实现equals方法的时候,在进行实质性的比较之前,先比较下类型是否一致是一个好的习惯
	    return value == ((Integer)obj).intValue();
	}
	return false;
    }
equals方法是对Integer中的成员变量alue进行了比较。

    public int hashCode() {
	return value;
    }
hashcode方法则是直接返回了成员变量value。

***********************************************************************************************************************

Integer类中有一部分类型转换的方法:

byteValue()、 shortValue()、intValue()、longValue()、floatValue()、doubleValue()
这些方法的内部实现都是直接进行了强制类型转换,在此就不多述。

***********************************************************************************************************************

类似于上面所介绍的int转String。有一个相对称的过程,则是把一个String转换为一个int值,这个过程则没有前一个那么简单,我们可以来看下源码:

public static int parseInt(String s, int radix)
		throws NumberFormatException
    {
        if (s == null) {//String为null,直接抛出异常
            throw new NumberFormatException("null");
        }

	if (radix < Character.MIN_RADIX) {//小于最小基数,抛异常
	    throw new NumberFormatException("radix " + radix +
					    " less than Character.MIN_RADIX");
	}

	if (radix > Character.MAX_RADIX) {//大于最大基数,抛异常
	    throw new NumberFormatException("radix " + radix +
					    " greater than Character.MAX_RADIX");
	}

	int result = 0;
	boolean negative = false;
	int i = 0, max = s.length();
	int limit;
	int multmin;
	int digit;

	if (max > 0) {
	    if (s.charAt(0) == '-') {
		negative = true;
		limit = Integer.MIN_VALUE;
		i++;
	    } else {
		limit = -Integer.MAX_VALUE;
	    }
	    multmin = limit / radix;
	    if (i < max) {
		digit = Character.digit(s.charAt(i++),radix);
		if (digit < 0) {
		    throw NumberFormatException.forInputString(s);
		} else {
		    result = -digit;
		}
	    }
	    while (i < max) {//循环处理过程
		// Accumulating negatively avoids surprises near MAX_VALUE
		digit = Character.digit(s.charAt(i++),radix);
		if (digit < 0) {
		    throw NumberFormatException.forInputString(s);
		}
		if (result < multmin) {
		    throw NumberFormatException.forInputString(s);
		}
		result *= radix;
		if (result < limit + digit) {
		    throw NumberFormatException.forInputString(s);
		}
		result -= digit;
	    }
	} else {
	    throw NumberFormatException.forInputString(s);
	}
	if (negative) {
	    if (i > 1) {
		return result;
	    } else {	/* Only got "-" */
		throw NumberFormatException.forInputString(s);
	    }
	} else {
	    return -result;
	}
    }
请注意这个循环处理过程。

Integer中的parseInt(String s) valueOf(String s, int radix)等方法都是建立在这个基础之上的,在此就不多述。

*******************************************************************************************************************************

下面介绍Integer中一个非常重要的知识点,那就是Integer中的内部类IntegerCache。顾名思义,这个内部类是个缓存类,那么他缓存了什么呢?

private static class IntegerCache {
        static final int high;
        static final Integer cache[];

        static {
            final int low = -128;

            // high value may be configured by property
            int h = 127;
            if (integerCacheHighPropValue != null) {
                // Use Long.decode here to avoid invoking methods that
                // require Integer's autoboxing cache to be initialized
                int i = Long.decode(integerCacheHighPropValue).intValue();
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - -low);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }

        private IntegerCache() {}
    }

从其源码中我们可以看出来,从-128到127的Integer对象都被它缓存了。。这就是论坛中很多人经常问到一些Integer对象==判断等否的问题了,正是因为这个缓存迷惑了大家。

当然,单纯上面这个内部类是不可能造成这样的影响的,最关键的地方是:

    public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
    }
这个方法,中使用到了这个缓存,而alueOf这个方法用的地方很多,Integer的自动拆装箱也是调用了这个方法,因此才会造成上面的问题。

*******************************************************************************************************************************************

Integer类中还有很多和位运算相关的方法,因为平时使用的较少,就不介绍了。比如如下方法:

reverse(int i)  rotateRight(int i, int distance) signum(int i) 等等

******************************************************************************************************************************************

本文出处:http://blog.csdn.net/gentleboy2009/article/details/7523087

转载请注明出处!

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值