如何在不复制数据的情况下在 Java 中获取数组的子数组?

2022-01-24 00:00:00 arrays containers java

我有一些类库,正在处理我的数据,这些数据正在读入缓冲区.是否有可能以某种方式避免一次又一次地复制数组,将部分数据越来越深地传递到处理方法中?好吧,这听起来很奇怪,但在我的特殊情况下,有一个特殊的编写器,它将数据分成块并将它们单独写入不同的位置,因此它只执行 System.arraycopy,获取它需要的内容并调用底层编写器,使用那个新的子数组.这种情况发生了很多次.重构此类代码的最佳方法是什么?

I have some library of classes, working with my data, which is being read into buffer. Is it possible somehow to avoid copying arrays again and again, passing parts of data deeper and deeper into processing methods? Well, it sounds strange, but in my particular case, there's a special writer, which divides data into blocks and writes them individually into different locations, so it just performs System.arraycopy, gets what it needs and calls underlying writer, with that new sub array. And this happens many times. What is the best approach to refactor such code?

推荐答案

Java 中的许多类都接受数组的子集作为参数.例如.Writer.write(char cbuf[], int off, int len).也许这对于您的用例已经足够了.

Many classes in Java accept a subset of an arrays as parameter. E.g. Writer.write(char cbuf[], int off, int len). Maybe this already suffices for your usecase.

相关文章