Possible Lossy conversion from long to int

匿名 (未验证) 提交于 2019-12-03 02:23:02

问题:

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

回答1:

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];   


回答2:

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



回答3:

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.



回答4:

  1. You cannot create an array with more than 2^31-1 entries, so you should use an int value when you do so (the compiler is simply warning you that the size will be truncated from long to int). 1000000000 is small enough to fit into int, so you basically have no reason to use long y in order to store this value in the first place.

  2. According to your description, the array itself is designated to store int values, so it doesn't need to be an array of long values.

In short, you can and should change every long in your code to int.



回答5:

I think you have some misconception about typecasting here. In Java down casting is allowed as already mentioned you can down cast it to integer

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

But here the main problem is that array allocation should takes integer value so that the same number of homogeneous space can be allocated. If you want more space than an integer range then you should use ArrayList which is dynamically grow-able array because if we give that much liability to a user to declare a large amount array memory then our system may run out of the memory as array is a static memory allocation data structure. The same stands true for

arr[j]=4; 

It should be:

arr[(int)j]=4; 


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