What is the difference between limit and capacity in ByteBuffer?

后端 未结 3 910
青春惊慌失措
青春惊慌失措 2020-12-23 03:26

What is the difference between limit and capacity in Java\'s java.nio.ByteBuffer?

3条回答
  •  臣服心动
    2020-12-23 03:56

    capacity is buffer's max size which is determined on buffer creation and never changes, limit is the actual size which can be changed. You cannot read or write beyond limit.

        ByteBuffer b= ByteBuffer.allocate(10); // capacity = 10, limit = 10
        b.limit(1);    //set limit to 1
        b.put((byte)1);
        b.put((byte)1); //causes java.nio.BufferOverflowException
    

提交回复
热议问题