在Java中:在哪里创建一个指向更大数组的一部分的子数组的方法? [英] In Java: is where a way to create a subarray that will point to a portion of a bigger array?

查看:89
本文介绍了在Java中:在哪里创建一个指向更大数组的一部分的子数组的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

学习Java,请温柔。理想情况下,我需要创建一个字节数组,指向更大数组的一部分:

Learning Java, so be gentle please. Ideally I need to create an array of bytes that will point to a portion of a bigger array:

byte[] big  = new byte[1000];

// C-style code starts
load(file,big);

byte[100] sub = big + 200; 

// C-style code ends

我知道这是不可能的在Java中,我想到了两种解决方法,包括:

I know this is not possible in Java and there are two work-arounds that come to mind and would include:


  1. 复制 big的一部分进入 sub 迭代 big

或者编写自己的类来获取参考 big + offset + size 并使用 big 作为实际底层数据结构,通过访问器方法实现子阵列。

Or writting own class that will take a reference to big + offset + size and implementing the "subarray" through accessor methods using big as the actual underlying data structure.

我要解决的任务是将文件加载到内存中,然后获取对通过类存储文件的记录的只读访问权限。速度是最重要的,因此理想情况下我想避免复制或访问方法。因为我正在学习Java,所以我想坚持下去。

The task I am trying to solve is to load a file into memory an then gain read-only access to the records stored withing the file through a class. The speed is paramount, hence ideally I'd like to avoid copying or accessor methods. And since I'm learning Java, I'd like to stick with it.

我还有其他选择吗?如果我没有充分解释任务,请提出问题。

Any other alternatives I've got? Please do ask questions if I didn't explain the task well enough.

推荐答案

创建一个数组作为一个视图其他数组在Java中是不可能的。但您可以使用 java.nio.ByteBuffer ,这基本上是你在解决方案#2中建议的课程。例如:

Creating an array as a "view" of an other array is not possible in Java. But you could use java.nio.ByteBuffer, which is basically the class you suggest in work-around #2. For instance:

ByteBuffer subBuf = ByteBuffer.wrap(big, 200, 100).slice().asReadOnlyBuffer();

不涉及复制(虽然创建了一些对象)。作为一个标准的库类,我还假设ByteBuffer更有可能接受特殊处理。 JVM的JIT优化比自定义优化。

No copying involved (some object creation, though). As a standard library class, I'd also assume that ByteBuffer is more likely to receive special treatment wrt. "JIT" optimizations by the JVM than a custom one.

这篇关于在Java中:在哪里创建一个指向更大数组的一部分的子数组的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆