在Java中使用一个只要ArrayList的指数 [英] Using a long as ArrayList index in java

查看:101
本文介绍了在Java中使用一个只要ArrayList的指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写这篇java程序找到所有的素数高达使用埃拉托色尼的筛NUM,但是当我尝试编译,它说我不能用长var当成数组的索引,它期待一个在它的地方INT变种。但我会用大量的合作,所以我不能使用int类型。我该怎么办?

 进口的java.util。*;
进口的java.lang。*;公共类T3 {
    公共静态无效的主要(字串[] args){
        长NUM = 100;        //声明列表,并与数字填充它
        ArrayList的<龙> numlist =新的ArrayList<龙>();
        为(长x = 2; X<民; X ++){
            numlist.add(新龙(X));
        }        //筛或埃拉托色尼
        为(长x = 0; X<的Math.sqrt(NUM); X ++){
            为(长Y = X + 1; Y< numlist.size(); Y ++){
                如果(numlist [Y]%numlist [X] == 0){
                    numlist.remove(Y);
                }
            }
        }        //打印列表
        对于(Object项:numlist){
            的System.out.println((长)项);
        }
    }
}


解决方案

我不知道为什么你的code将汇编开始。

你不应该使用[]数组中的列表访问的成员。一个ArrayList的仅仅是在内部存储在数组中的列表。你必须使用列表get操作(这将仍然是O(1))。写作numlist [指数]是指你在numlist对象的数组。你不能覆盖的[]操作在C ++中。

在此外,int是用Java 32位。其长度大于数组2 ^ 32(所以你需要长指数)是不可能的,我甚至不知道在规范允许的。

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);
        }
    }
}

解决方案

I'm not sure why your code would compile to begin with.

You're not supposed to use [] in an array list to access members. An arraylist is merely a list that is internally stored in an array. You have to use the list get operation (which would still be O(1)). Writing numlist[index] means that you have an array of objects in numlist. You cannot override the [] operation as in C++.

In addition, an int is 32 bits in Java. Having an array of length greater than 2^32 (so you would need long indices) is unlikely and I'm not even sure the specification allows it.

这篇关于在Java中使用一个只要ArrayList的指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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