java包装类之Integer类源码分析

20 篇文章 0 订阅
3 篇文章 0 订阅

Integer类是实体类中必不可少的一个包装类型,其它类中可能也会用到,下面我来讲讲Integer类的源码分析:

/**
 *@author nice
 *继承了Number类实现了Comparable<Integer>接口
 */
public final class Integer extends Number implements Comparable<Integer>
{
	/**
	  *最小值
	  */
	@Native public static final int   MIN_VALUE = 0x80000000;
	/**
	  *最大值
	  */
	@Native public static final int   MAX_VALUE = 0x7fffffff;
	@SuppressWarnings("unchecked")
    public static final Class<Integer>  TYPE = (Class<Integer>) Class.getPrimitiveClass("int");
    /**
      *打印成字符串
      */
    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));
    }
    /**
     *转成16进制字符串
     */
    public static String toHexString(int i) {
        return toUnsignedString0(i, 4);
    }
    /**
      *转成8进制字符串
      */
    public static String toOctalString(int i) {
        return toUnsignedString0(i, 3);
    }
    /**
      *转成2进制字符串
      */
    public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
    }
    /**
      *转换成对应进制的字符串
      */
    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
        char[] buf = new char[chars];

        formatUnsignedInt(val, shift, buf, 0, chars);

        // Use special constructor which takes over "buf".
        return new String(buf, true);
    }
    /**
      *将int类型转换为字符串
      */
    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);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值