Is it somehow possible to use a long int to index an array? Or is this not allowed?
What I mean is bellow in the code.
long x = 20;
char[] array = ne
No, it's not possible. JLS 15.10 states that the expression in an array initializer must be promoted to an int
:
Each dimension expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.
Same thing with applies to array access expressions (JLS 15.13):
The index expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.
If you want to use a long
, you'll have to cast it to int
first:
char[] array = new char[(int) x];
res = array[(int) x];
Technically you can have such a structure using Unsafe
class. with it you can allocate as much memory as you want (as you have actually). To be noted that this is native memory and not heap memory. Because of this, there are downsides as compared to typical arrays, though: the memory isn't garbage collected (you'll need to manually deallocate memory) and there aren't bound checks so without being careful you can have seg fault and crash your JVM.
See example here, at Big Array section: http://mishadoff.com/blog/java-magic-part-4-sun-dot-misc-dot-unsafe/
Also there are rumors that future versions of JVM and the language will have support arrays of size long
.
If you look at the Java Documentation in 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.
The error you would get would look something like this:
test.java:12: possible loss of precision
found : long
required: int
System.out.println(array[index]);
^
1 error
If for some reason you have an index stored in a long, just cast it to an int and then index your array. You cannot create an array large enough so it cannot be indexed by an integer in Java. So there is no need for long integers here.