现在的位置: 首页 > 综合 > 正文

Byte类分析

2013年09月08日 ⁄ 综合 ⁄ 共 2242字 ⁄ 字号 评论关闭

       Number类是java中几个基本数据类型之封装类的基类。内容比较简单,只定义了子类中用到的几个方法。Byte是Number的子类。
       在Byte的类定义中可以看到,它只是对byte的简单封装,其中定义了MIN_VALUE和MAX_VALUE作为byte的上下界,对应的byte的值保存在 private final byte value;中。下面分析一下里面几个比较有意思的地方:
1.静态内部类ByteCache。

private static class ByteCache {
    
private ByteCache(){}
    
static final Byte cache[] = new Byte[-(-128+ 127 + 1];
    
static {
        
for(int i = 0; i < cache.length; i++)
        cache[i] 
= new Byte((byte)(i - 128));
    }

    }

这里创建了一个256个元素的Byte数组cache,用来预先创建并保存各个byte值对应的Byte对象。数组大小用-(-128)+127+1指定,为什么不简单的使用256来说明呢?只是为了说明byte表示的范围有-128~-1,0,127三个部分组成吗?
ByteCache就是在通过byte值创建Byte对象时使用:

public static Byte valueOf(byte b) {
    
final int offset = 128;
    
return ByteCache.cache[(int)b + offset];
    }

这样处理估计是出于对效率的考虑。
2.Byte的toString()和parseByte()方法都是通过调用Integer的相应方法来实现的,设计到强制类型转换。
3.decode方法的实现:从String创建Byte对象。

public static Byte decode(String nm) throws NumberFormatException {
        
int radix = 10;
        
int index = 0;
        
boolean negative = false;
        Byte result;

        
// Handle minus sign, if present
        if (nm.startsWith("-")) {
            negative 
= true;
            index
++;
        }


    
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
            index 
+= 2;
            radix 
= 16;
    }
 else if (nm.startsWith("#", index)) {
        index
++;
            radix 
= 16;
    }
 else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
        index
++;
            radix 
= 8;
    }


        
if (nm.startsWith("-", index))
            
throw new NumberFormatException("Negative sign in wrong position");

        
try {
            result 
= Byte.valueOf(nm.substring(index), radix);
            result 
= negative ? new Byte((byte)-result.byteValue()) : result;
        }
 catch (NumberFormatException e) {
            
// If number is Byte.MIN_VALUE, we'll end up here. The next line
            
// handles this case, and causes any genuine format error to be
            
// rethrown.
            String constant = negative ? new String("-" + nm.substring(index))
                                       : nm.substring(index);
            result 
= Byte.valueOf(constant, radix);
        }

        
return result;
    }

注意一下对八进制情况的处理,以0开头但不是0。
      因为类比较简单,所以分析比较容易。关键是能否通过该类的设计自己推出其他相对复杂一些的封装类的实现方式。比如我应该如何设计Short,Integer等。

【上篇】
【下篇】

抱歉!评论已关闭.