简体   繁体   中英

How to declare array to type long in java?

I am trying to execute this code:

long n = in.nextLong();
    long k = in.nextLong();
    long[][] arr = new long[n][2];

But the is Compiler showing this error-

Main.java:9: error: incompatible types: possible lossy conversion from long to int


long[][] arr = new long[n][2];

Can someone explain why this is happening?

In new long[n][2] , both n and 2 are array dimension sizes, so they should be type int , not long . Even if the array itself holds long values.

Change your first line of code to

int n = in.nextInt();

The error you are getting is because you're trying to use a long as an integer. The indices of arrays are always integers. Java prevents you from converting from long to int because you are removing 32-bits of information.

Arrays use integers as indexes. So the long is converted to int in order to be used as index. Hence the error being shown as you could have input something larger than what a int can hold which on conversion to int would cause loss of information.

Main.java:9: error: incompatible types: possible lossy conversion from long to int

Also since you cannot create a array large enough that it is beyond the range of int to index it so int were chosen as datatype to index arrays.

array index is always int and you are trying to assign long to index hence the error, long has 8 bytes while int has 4 bytes so if you try to covert long to int then there may be chance of loss of precision and compiler won't allow this. By default any digit value is treated as int in java, use int value for array index , in your code simple type casting should work try

long[][] arr= new long [(int)n][2];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM