你能用 long int 索引一个数组吗? [英] Can you index an array with a long int?

查看:28
本文介绍了你能用 long int 索引一个数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用 long int 来索引数组?或者这是不允许的?

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

我的意思是在代码中.

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

long x = 5;
char res;
res = array[x];

推荐答案

如果你看一下 Java 文档 10.4:

If you look at the Java Documentation in 10.4:

数组必须由 int 值索引;short、byte 或 char 值可能也可以用作索引值,因为它们是一元的数字提升(第 5.6.1 节)并成为 int 值.

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

如果由于某种原因您将索引存储在 long 中,只需将其转换为 int 然后索引您的数组.你不能创建一个足够大的数组,所以它不能在 Java 中被整数索引.所以这里不需要长整数.

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.

这篇关于你能用 long int 索引一个数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆