Possibly lossy conversion from long to int [duplicate]

家住魔仙堡 提交于 2019-12-31 06:25:28

问题


I am getting "incompatible types: possibly loss of conversion from long to int" exception in this line: boolean arr[] = new boolean [limit]; I don't understand why this is happening since I am storing the input value in long, how is it getting converted to int?

 import java.util.*;
 import java.io.*;
 public class PrimeSieve
{
public static void main (String args [])
{
   //getting the number
   Scanner x = new Scanner (System.in);
   System.out.println("What is your number?");
   long limit = x.nextLong();
   long count = 0;

   //making all the numbers upto the given number prime
   boolean arr[] = new boolean [limit]; 
   for ( long i = 2; i <=Math.sqrt(limit); i++) 
   {
       arr[i] = true;
   }

回答1:


This because you are using a long as a size for an array.

Java supports array up to a certain limit which is around Integer.MAX_VALUE - x (see this) so using a long to specify the size is not allowed.

Quoting from JLS:

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.




回答2:


Array lengths and indices must always be ints. You cannot create an array with long length, nor can you refer to a long index in an array.



来源:https://stackoverflow.com/questions/31144675/possibly-lossy-conversion-from-long-to-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!