将’int’转换为’long’或使用’long’访问太长的数组

假设我有一个足够长的数组,可以用int访问它的任何索引,有没有办法用int来访问这样一个数组的索引? 以及Java如何处理这种数组? 例:

 int[] a = new int[]{1,5,2,4........9,2,1} 

假设在上面的数组中, 9,2,1处于超出int (2 31 )范围的索引处。 我如何访问这些元素?

你不会 – 数组索引在Java中总是int值。 它不允许具有多于Integer.MAX_VALUE元素的数组。

数组的lengthlength字段表示,其类型为int 。 因此,无法创建长度大于Integer.MAX_VALUE的数组。

规范没有明确地将其解析出来,但您可以从涉及的类型中推断出来。

你不能拥有那么长的数组。 但是这个想法已经被提出用于项目硬币。

数组必须用int值索引; shortbytechar值也可以用作索引值,因为它们受到一元数字提升(第5.6.1节)并成为int值。 尝试访问具有long索引值的数组组件会导致编译时错误


资源:

  • JLS – arrays访问
  • JLS – 数组创建表达式
  • 项目硬币 – 大arraysV1 – V2

正如其他人所提到的,长度和索引值必须是整数。 如果你确实需要这个,那么有一些解决方法。 例如,您可以拥有一个非常大的int数组数组。 然后,您可以对long执行一些模运算,以确定您需要哪个数组以及该数组中需要哪个索引。

你需要一个自定义数据结构,试试这个:

 /** * Because java uses signed primitives only the least significant 31 bits of an int are used to index arrays, * therefore only the least significant 62 bits of a long are used to index a LongArray * * @author aaron */ public class LongArray { //inclusive public static final long maximumSize = (~0)>>>2;//0x 00 FF FF FF FF FF FF FF public static final long minimumSize = 0; //Generic arrays are forbidden! Yay dogma! private Object[][] backingArray; private static int[] split(long L) { int[] rtn = new int[2]; rtn[1] = Integer.MAX_VALUE & (int)(L>>7); rtn[0] = Integer.MAX_VALUE & (int)L; return rtn; } private static long join(int[] ia) { long rtn = 0; rtn |= ia[0]; rtn <<= 7; rtn |= ia[1]; return rtn; } private static boolean isValidSize(long L) { return L<=maximumSize && L>=minimumSize; } public LongArray(long size){ if (!isValidSize(size)) throw new IllegalArgumentException("Size requested was invalid, too big or negative"); //This initialises the arrays to be only the size we need them to be int[] sizes = split(size); backingArray = new Object[sizes[0]][]; for (int index = 0; index