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

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

问题描述

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

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];

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


推荐答案

如果你看一下 10.4文档中的Java文档


数组必须用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天全站免登陆