java - 你能用一个 long int 索引一个数组吗?

标签 java arrays

是否可以通过某种方式使用 long int 来索引数组?或者这是不允许的?

我的意思是下面的代码。

long x = 20;
char[] array = new char[x];

long x = 5;
char res;
res = array[x];

最佳答案

如果您查看 Java Documentation在 10.4 中:

Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6.1) and become int values.

An attempt to access an array component with a long index value results in a compile-time error.

你会得到的错误看起来像这样:

test.java:12: possible loss of precision
found   : long
required: int
        System.out.println(array[index]);
                                 ^
1 error

如果出于某种原因你有一个索引存储在一个 long 中,只需将它转换为一个 int 然后索引你的数组。您不能创建足够大的数组,因此它不能在 Java 中由整数索引。所以这里不需要长整数。

关于java - 你能用一个 long int 索引一个数组吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27333879/

相关文章:

python - 为什么 NumPy 数组优于标准库数组?

java - 接口(interface)和实现的名称,哪个更好?

java - 如何打印出当前在特定非线程类上运行的线程名称?

java - 使用 ExecutorService 时如何避免 "cannot create native threads"?

python - 计算 ndarray 中每列的 Nan 值

c++ - C++ 中 Armadillo 矩阵维度的动态参数化

java - 在 micronaut 中为集成测试配置数据库

java - Lucene:从索引中删除,基于多个字段

javascript - 为 Angular 动态数据生成嵌套结构

php - 使用 php 从查询 mysql 创建姓名和电子邮件