Using a long as ArrayList index in java

时间:2023-03-10 05:05:14
Using a long as ArrayList index in java

http://*.com/questions/459643/using-a-long-as-arraylist-index-in-java

http://bbs.csdn.net/topics/390207278

——————————————————————————————————————————————————————————

I am writing this java program to find all the prime numbers up to num using the Sieve of Eratosthenes, but when I try to compile, it says I can't use a long var as an array index, and it expects an int var in its place. But I'll be working with large numbers, so I can't use int. What can I do?

import java.util.*;
import java.lang.*; public class t3{
public static void main(String[] args){
long num = 100; //declaring list and filling it with numbers
ArrayList<Long> numlist = new ArrayList<Long>();
for(long x=2 ; x<num ; x++){
numlist.add(new Long(x));
} //sieve or eratosthenes
for(long x=0 ; x<Math.sqrt(num) ; x++){
for(long y=x+1 ; y<numlist.size() ; y++){
if(numlist[y]%numlist[x] == 0){
numlist.remove(y);
}
}
} //print list
for(Object item : numlist){
System.out.println((Long)item);
}
}
}

————————————————————————————————————————————————————————————

刚刚去国外网站搜到如下解释:
http://*.com/questions/459643/using-a-long-as-arraylist-index-in-java

The bytecode only allows int sized and indexed arrays, so there would have to be a (fairly major) change to the class file format to allow this.

Realize that with a 32-bit signed int index to a long[] you're addressing 16GB of RAM.

The Java specification limits arrays to at most Integer.MAX_VALUE elements. While a List may contain more elements (this is true for Collections in general), you can only add/get/remove/set them using an int index.

Assuming you have the memory for that many elements (very unlikely I think), you could write your own data structure consisting of "concatenated" arrays. The get() and set() methods would take a long index and figure out the corresponding array and int index within that array.

Also, I would suggest using booleans to represent the state of each number, instead of storing/removing each number explicitly. This would be better because (1) booleans take less space than longs, and (2) shifting elements (as done in ArrayList) during element removal can be expensive.

There have been proposals to add long-indexed arrays to Java via Project Coin ( http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000869.html ) although nothing has been accepted or scheduled.

总结起来就是:
1.字节码不容许
2.用long做脚标需要至少16G内存
3.可以用连接数组自行实现使用long为脚标的数据结构(建议使用一个boolean来替代保存,删除操作)
4.已有建议java使用long脚标数组的提议,未被采用罢了