Can you index an array with a long int?

Is it possible to use a long int to index an array? Or is it not allowed?

What do I mean below in the code.

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

or

long x = 5;
char res;
res = array[x];
+4
source share
3 answers

If you look at the Java Documentation in 10.4:

Arrays must be indexed with int values; short, byte, or char values ​​can also be used as index values, since they undergo unary numeric promotion (§5.6.1) and an int value.

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

The error you received will look something like this:

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

- , long, int . , Java. , .

+5

, . JLS 15.10 , int:

(§5.6.1). int, .

(JLS 15.13):

(§5.6.1). int, .

long, int:

char[] array = new char[(int) x];
res = array[(int) x];
+4

​​, Unsafe. , ( ). , , . - , : ( ), , , , JVM.

. , Big Array: http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/

It is also rumored that future versions of the JVM and language will contain size support arrays long.

+2
source

All Articles