Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you index an array with a long int?

Tags:

java

arrays

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 = new char[x];

or

long x = 5;
char res;
res = array[x];
like image 636
Martin Plávek Avatar asked Dec 06 '14 16:12

Martin Plávek


2 Answers

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.

like image 193
Joel Avatar answered Oct 09 '22 05:10

Joel


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.

like image 35
Random42 Avatar answered Oct 09 '22 05:10

Random42