JDK - ByteBuffer源码粗读

2016-10-04  本文已影响0人  麻瓜镇

ByteBuffer 的基类是 Buffer , Buffer 是一个抽象类,定义了4个基本的属性:

// Invariants: mark <= position <= limit <= capacity
private int mark = -1;
private int position = 0;
private int limit;
private int capacity;

ByteBuffer 在此基础上又定义了两个成员:

final byte[] hb;                  // Non-null only for heap buffers
final int offset;

从注释可以看出,hb 是只有heap buffer会用到,这里说的heap buffer就是 ByteBuffer 的子类 HeapByteBuffer ,这也是我们后面的阅读重点,因为大部分时候我们使用ByteBuffer 其实就是用的 HeapByteBuffer

ByteBuffer 的初始化方式主要有很多,因为其核心属性是final byte[] hb , 所以初始化主要就是分为两类:
一类是由ByteBufferallocate 方法来初始化:

public static ByteBuffer allocate(int capacity) {
    if (capacity < 0)
        throw new IllegalArgumentException();
    return new HeapByteBuffer(capacity, capacity);
}

我们可以看到,这里直接new出来了一个HeapByteBuffer对象。
另一类是提前初始化好的byte[],作为参数传进构造函数来初始化:

ByteBuffer(int mark, int pos, int lim, int cap,   // package-private
             byte[] hb, int offset){
    super(mark, pos, lim, cap);
    this.hb = hb;
    this.offset = offset;
}

或者通过wrap方法,生成一个HeapByteBuffer:

public static ByteBuffer wrap(byte[] array,
                                int offset, int length){
    try {
        return new HeapByteBuffer(array, offset, length);
    } catch (IllegalArgumentException x) {
        throw new IndexOutOfBoundsException();
    }
}

ByteBuffer 除了继承了Buffer类之外,还实现了Comparable接口,两个ByteBuffer比较时,比较的是ByteBuffer中剩余的byte数组,从当前的position开始,一直比较到最后一个byte:

public int compareTo(ByteBuffer that) {
    int n = this.position() + Math.min(this.remaining(), that.remaining());
    for (int i = this.position(), j = that.position(); i < n; i++, j++) {
        int cmp = compare(this.get(i), that.get(j));
        if (cmp != 0)
            return cmp;
    }
    return this.remaining() - that.remaining();
}

private static int compare(byte x, byte y) {
    return Byte.compare(x, y);
}

ByteBuffer 还实现了equals方法,提供了比较两个Buffer的功能:

public boolean equals(Object ob) {
    //如果是同一个对象,那么相等
    if (this == ob)
        return true;
    //如果比较对象不是ByteBuffer对象,那么肯定不相等
    if (!(ob instanceof ByteBuffer))
        return false;
    ByteBuffer that = (ByteBuffer)ob;
    //如果两个Buffer剩余的byte数目不一样多,肯定不相等 
    if (this.remaining() != that.remaining())
        return false;
    //从Buffer的末尾开始比较
    int p = this.position();
    for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--)
        if (!equals(this.get(i), that.get(j)))
            return false;
    return true;
}

private static boolean equals(byte x, byte y) {
    return x == y;
}
上一篇 下一篇

猜你喜欢

热点阅读