Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible Lossy conversion from long to int [duplicate]

I wish to enter one int and another long ex: 1 and 1000000000, and now I wish to create an array of size 1000000000. And then at each index of array, store int val, ex: arr[100000000] = 4.

When I'm trying to do this Netbeans shows me an error in this line:

arr = new long[y+1]` and `arr[j] = 0` 

"Possible Lossy conversion from long to int". Here's my code:-

public static void main(String[] args) throws IOException       
{     
    BufferedReader s = new BufferedReader(new InputStreamReader(System.in));           
    String[] xe = s.readLine().split(" ");          
    int x = Integer.parseInt(xe[0]);        
    long y = Long.parseLong(xe[1]);
    long []arr;    
    arr = new long[y+1];     
    for(long j=0;j<=y;j++)     
    arr[j] = 4;     
} 
like image 736
ranaarjun Avatar asked Feb 17 '14 11:02

ranaarjun


3 Answers

Array index is an integer in Java and the compiler will advice you. So maximum array size is (aproximately) Integer.MAX_VALUE. For bigger arrays you should use ArrayList.

To go around this dirt&quick

arr = new long[(int)y+1];  
like image 111
PeterMmm Avatar answered Oct 28 '22 05:10

PeterMmm


The size of an array can only be an int. That is you, can not create arrays that are larger than Integer.MAX_VALUE (2147483647), probably a few elements less (depending on the VM). You can cast your value to int

arr = new long[(int)(y+1)];

but this will produce invalid results when the value of y is actually larger than the maximum allowed size.

like image 21
Marco13 Avatar answered Oct 28 '22 04:10

Marco13


You need to convert/cast y and j to int. Also your incrementing var shouldn't be long when you're just adding 1.

like image 37
Leo Pflug Avatar answered Oct 28 '22 03:10

Leo Pflug