源码分析(2)-包装类源码分析

1. 回顾基本数据类型

说到包装类肯定要提到java的八种基本数据类型:byte,char,short,int,long,double,float,boolean。

数据类型位数默认值取值范围
byte(位)80-2^7 - 2^7-1
short(短整数)160-2^15 - 2^15-1
int(整数)320-2^31 - 2^31-1
long(长整数)640-2^63 - 2^63-1
float(单精度)320.0-2^31 - 2^31-1
double(双精度)640.0-2^63 - 2^63-1
char(字符)160 - 2^16-1
boolean(布尔值)8falsetrue、false

2.包装类

根据基本数据类型的种类,可以知道包装类也有八种。分别是:Byte,Character,Short,Integer,Long,Float,Double。由于每种包装类型都要很多方法,这里不会进行一一介绍,主要会介绍几种常用的方法。

2.1 valueOf

这是所有包装类型都有的一个方法,它可以将字符串或者其基本数据类型的数值转换为包装类型,而且它使用了缓存可以减少二次创建的消耗。

2.1.1 Boolean

    public static final Boolean TRUE = new Boolean(true);
    public static final Boolean FALSE = new Boolean(false);
    public static Boolean valueOf(boolean b) {
        return (b ? TRUE : FALSE);
    }

由于Boolean类型是比较特殊的一种包装类型,它只有两种结果,所以在加载Boolean类就已经创建好了TURE和FALSE这两种Boolean类型对象。

2.1.2 Byte

    private static class ByteCache {
        private ByteCache(){}

        static final Byte cache[] = new Byte[-(-128) + 127 + 1];
       
       // 加载ByteCache 类时将将所有的Byte实例加载到内存
        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }

// 直接从缓存中获取实例
public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }

ByteCache缓存了Byte包含的所有实例,valueOf直接可以从缓存中获取。(由于Short和Long类型表示的数值较大,所以只是缓存了-128-127区间的实例。而Character类型没有负数只缓存了0-127之间的实例。唯独经常使用的Integer不一样,它可以被人为控制,具体看下面的介绍)

2.1.3 Integer

    private static class IntegerCache {
        // 缓存的最小值:-128
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // 默认的缓存最大值是127
            int h = 127;
            // 读取java.lang.Integer.IntegerCache.high的属性值,用于确定缓存的最大值
            String integerCacheHighPropValue =
               sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // 一个数组最大的长度是一个 int 的最大值
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

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

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

  public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
            // 超过缓存直接创建
        return new Integer(i);
    }

Integer是使用频率最高的包装类,所以可以根据使用的范围或者频率设置需要缓存的区间。

2.1.4 Double

public static Double valueOf(double d) {
        return new Double(d);
    }

由于double类型的数值范围太大,valueOf就是使用new的方式创建实例(Float包装类也是这样的)

2.parseXXX

将字符串类型转换为基本数据类型

2.2.1 Boolean

    public static boolean parseBoolean(String s) {
        return ((s != null) && s.equalsIgnoreCase("true"));
    }

这个比较简单,就是在忽略大小写的情况下为字符串true就判定为布尔类型的true

2.2.2 Character

没有parseCharacter(String s)方法

2.2.3 Short

    public static short parseShort(String s) throws NumberFormatException {
        // 10对应的是十进制
        return parseShort(s, 10);
    }
    public static short parseShort(String s, int radix)
        throws NumberFormatException {
        int i = Integer.parseInt(s, radix);
        // 判断范围
        if (i < MIN_VALUE || i > MAX_VALUE)
            throw new NumberFormatException(
                "Value out of range. Value:\"" + s + "\" Radix:" + radix);
        return (short)i;
    }

2.2.4 Integer

public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
    }
public static int parseInt(String s, int radix)
                throws NumberFormatException
    {
        if (s == 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, len = s.length();
        int limit = -Integer.MAX_VALUE;
        int multmin;
        int digit;

        if (len > 0) {
            char firstChar = s.charAt(0);
            // 通过第一个字符判断正负
            if (firstChar < '0') { // Possible leading "+" or "-"
                if (firstChar == '-') {
                    negative = true;
                    limit = Integer.MIN_VALUE;
                } else if (firstChar != '+')
                    throw NumberFormatException.forInputString(s);
                // 不能只有+/-
                if (len == 1) 
                    throw NumberFormatException.forInputString(s);
                i++;
            }
            multmin = limit / radix;
            while (i < len) {
                // 将字符转换为对应的数字(比如: '2' -> 2)
                digit = Character.digit(s.charAt(i++),radix);
                if (digit < 0) {
                    throw NumberFormatException.forInputString(s);
                }
                // result < limit / radix => result * radix  < limit 
                if (result < multmin) {
                    throw NumberFormatException.forInputString(s);
                }
                result *= radix;
                if (result < limit + digit) {
                    throw NumberFormatException.forInputString(s);
                }
                // 使用负数的形式表示,所以当negative表示非负时要加负号,即negative ? result : -result
                result -= digit;
            }
        } else {
            throw NumberFormatException.forInputString(s);
        }
        return negative ? result : -result;
    }

Long类型的parseLong方法和Integer的差不多,不做多介绍

2.Double

 public static double parseDouble(String s) throws NumberFormatException {
 // 调用FloatingDecimal的parseDouble方法,比处理Integer会复杂一点,关键在于处理NaN,Infinity,e/E,f/F等特殊的字符串
        return FloatingDecimal.parseDouble(s);
    }

Float和Double处理方式一样

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值