是否可以通过某种方式使用 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/