Java:如何获取ShortBuffer中的项目数?

huangapple go评论78阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2020年10月14日 16:59:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64349898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定