Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
109 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...