如果在Java中使用长数据类型,则访问数组元素 [英] Accessing an array element if using long datatype in Java

查看:84
本文介绍了如果在Java中使用长数据类型,则访问数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java解决竞争性编程问题。在涉及数组使用的问题中,我将不得不编写程序,使数组可以容纳大量值(超出 int 的范围),而且每个数组元素也都超出了 int 范围。
所以我为此使用 long 。但是,如果我尝试访问

I am trying to solve competitive programming questions using Java. In questions involving the use of arrays, I will have to write my programs such that the array can hold a large number of values(beyond the range of int) and also each array element is also beyond the int range. So I am using long for this. But if I try accessing say

 a[i++] = b[j++];

其中, & & b都是 long 类型,我得到以下错误:

where i & j & a& b are all of long type, I get the following error:

  error: possible loss of precision

用于索引访问。

如何我如何访问这些元素?我尝试将 long 转换为 int 来获取索引值,并且错误消失了,但是那也不会影响精度吗?

How do I access such elements? I tried typecast of long to int for the index values, and the error goes away, but won't that affect the precision too?

变量声明如下:

long numTest = in.nextLong();

    long [] sizes = new long[numTest];

推荐答案

Java语言规范指出,不能将long用作数组索引:

The Java Language Specification says that you can't use longs as array indexes:


必须使用int值对数组进行索引...尝试访问具有长索引值的数组组件会导致编译时错误。

Arrays must be indexed by int values... An attempt to access an array component with a long index value results in a compile-time error.

所以您可以期望最大大小为Integer.MAX_VALUE,但这取决于您讨论的JVM 此处

So you could expect that tha maximum size would be Integer.MAX_VALUE, but that depends on your JVM which is discussed here

这篇关于如果在Java中使用长数据类型,则访问数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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