英文:
Java: How to get the number of items in a ShortBuffer?
问题
我想知道如何获取 ShortBuffer 中的项目数。
我想要的是实际在缓冲区中的项目数量,而不是最大容量。
谢谢。
英文:
I wonder how to get the number of items in a ShortBuffer.
I want the number of items that are really in the buffer, not the maximum capacity.
Thanks.
答案1
得分: 1
Buffer 不是一个集合,而是一个(相对较薄的)原始数组包装器,为对一组原始值执行操作提供了一些有用的方法。与原始数组一样,它始终包含每个有效索引的值。
因此,项数总是等于其容量。
它不会跟踪自创建以来已写入哪些索引。并且,一个主要的用例是在仍反映对包装数组的所有更改的情况下包装现有数组,甚至不可能实现。
英文:
Buffer is not a Collection, but a (comparatively thin) wrapper around a primitive array that provides some useful methods for operating on groups of primitive values. Like a primitive array, it always contains values for each valid index.
Therefore the number of items is always equal to its capacity.
It does not keep track of which indices have already been written to since its creation. And as one major use case is to wrap an existing array while still reflecting all changes to the wrapped array, that would not even be possible to implement.
答案2
得分: 0
ShortBuffer
保存一个position
,用于跟踪要put
元素的位置。您可以使用它来了解您放入了多少元素。元素的数量始终等于其容量,就像其他人提到的那样。
@Test
fun testShortBuffer() {
val shortBuffer = ShortBuffer.allocate(1024)
println(shortBuffer.position()) // 位置 0
shortBuffer.put(1)
println(shortBuffer.position()) // 位置 1
shortBuffer.put(shortArrayOf(2, 3, 4))
println(shortBuffer.position()) // 位置 4
shortBuffer.clear()
println(shortBuffer.position()) // 位置 0
}
英文:
ShortBuffer
holds a position
that keeps track on where to put
elements. You can use it to know how many elements you put in. The number of elements always equals its capacity as others mentioned.
@Test
fun testShortBuffer() {
val shortBuffer = ShortBuffer.allocate(1024)
println(shortBuffer.position()) // position 0
shortBuffer.put(1)
println(shortBuffer.position()) // position 1
shortBuffer.put(shortArrayOf(2, 3, 4))
println(shortBuffer.position()) // position 4
shortBuffer.clear()
println(shortBuffer.position()) // position 0
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论