What is the difference between limit and capacity in ByteBuffer?

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

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

相关标签:
3条回答
  • 2020-12-23 03:55

    Its best illustrated HERE in this article: They are mainly different depending on the mode,

    • In Write Mode, Capacity and Limit are Same.
    • But in Read mode Limit means the limit of how much data you can read from the data

    enter image description here

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-23 04:01

    ByteBuffer does not have a length() method. Instead it has a several length-like concepts:

    mark <= position <= limit <= capacity
    

    capacity = Inside the ByteBuffer, there is a backing byte[] or something that behaves much like one. The capacity is its size. The capacity indexes the first slot past the end of the buffer.

    limit = When filling the buffer, the limit is the same as the capacity. When emptying the buffer, it is one past the last filled byte in the buffer.

    position = When filling the buffer, the position points just past the last byte filled in the buffer. When emptying the buffer, the position points just past the last byte written from the buffer.

    mark The mark is an optional bookmark to let you record an interesting spot in the ByteBuffer that you want to return to later. When you take a mark() it records current position, and when you call reset() it restores that position.

    I hope this helps. Also an example can be seen over here: http://mindprod.com/jgloss/bytebuffer.html

    Source: Oracle Java Buffer reference - See 'Invariants' section.

    0 讨论(0)
提交回复
热议问题