Java ByteBuffer 中的限制和容量有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23148729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between limit and capacity in ByteBuffer?
提问by Yuhao
What is the difference between limit and capacity in Java's java.nio.ByteBuffer?
Java 的java.nio.ByteBuffer 中的限制和容量有什么区别?
采纳答案by Santosh
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 Readmode Limit means the limit of how much data you can read from the data
- 在写入模式下,容量和限制相同。
- 但是在读取模式下限制意味着您可以从数据中读取多少数据
回答by Csuki
ByteBuffer
does not have a length()
method. Instead it has a several length-like concepts:
ByteBuffer
没有length()
方法。相反,它有几个类似长度的概念:
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.
capacity
= 在 内部ByteBuffer
,有一个支持byte[]
或类似的东西。容量就是它的大小。容量索引超出缓冲区末尾的第一个槽。
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.
limit
= 填充缓冲区时,限制与容量相同。清空缓冲区时,它是缓冲区中最后一个填充字节的后一个。
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.
position
= 填充缓冲区时,位置刚好经过缓冲区中填充的最后一个字节。清空缓冲区时,位置刚好超过从缓冲区写入的最后一个字节。
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.
mark
该标记是一个可选的书签,可让您在ByteBuffer
以后想要返回的地方记录一个有趣的地方。当你选择mark()
它时,它会记录当前的位置,当你调用reset()
它时,它会恢复那个位置。
I hope this helps. Also an example can be seen over here: http://mindprod.com/jgloss/bytebuffer.html
我希望这有帮助。也可以在这里看到一个例子:http: //mindprod.com/jgloss/bytebuffer.html
Source: Oracle Java Buffer reference- See 'Invariants' section.
来源:Oracle Java Buffer 参考- 请参阅“不变量”部分。
回答by Evgeniy Dorofeev
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