ByteBuffer 学习

ByteBuffer

实现类

  1. 堆外内存的方式 > DirectByteBuffer
public static ByteBuffer allocateDirect(int capacity) {
        return new DirectByteBuffer(capacity);
    }

  1. 堆内内存的方式 > HeapByteBuffer
public static ByteBuffer allocate(int capacity) {
        if (capacity < 0)
            throw new IllegalArgumentException();
        return new HeapByteBuffer(capacity, capacity);
    }

申请方法:

ByteBuffer byteBuffer = ByteBuffer.allocate(10);
ByteBuffer byteBuffer1 = ByteBuffer.allocateDirect(10); 

接下来以堆内内存的方式
主要参数:mark,position,limit,capacity
常见操作:

  1. putXXX
    在这里插入图片描述

影响position

putXXX(T t)
// position++;
// position<=limit;
// limit=capacity
// java中char占两个字节,区分大小端放入内存中, 
// 调用了Bits.putChar(this, ix(nextPutIndex(2)), x, bigEndian);
// 其他的类型也是类似的原理
putChar(char c)

不影响position

// 事先检查index是否合法

putXXX(int index,T t);
putChar(int i, char x);
  1. getXXX()方法
    在这里插入图片描述
    调用读方法之前需要调用
// limit = position
// position = 0
flip()

影响position

// position++; position<=limit
getXXX()
// getDouble()源码,和put方法过程相反
public double getDouble() {
return Bits.getDouble(this, ix(nextGetIndex(8)), bigEndian);
}

不影响position

getXXX(int index)

clean()

// 初始状态,但是没有清楚原来的数据
// position = 0;
// limit = capacity;
// mark = -1;
position =0

影响mark

mark(),reset()

posted @ 2019-04-17 17:15  dyigstraw  阅读(142)  评论(0编辑  收藏  举报
foot