What is the difference between limit and capacity in ByteBuffer?

Java

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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: http://docs.oracle.com/javase/7/docs/api/java/nio/Buffer.html">Oracle Java Buffer reference - See 'Invariants' section.

Solution 3 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYuhaoView Question on Stackoverflow
Solution 1 - JavaSantoshView Answer on Stackoverflow
Solution 2 - JavaCsukiView Answer on Stackoverflow
Solution 3 - JavaEvgeniy DorofeevView Answer on Stackoverflow