Reputation:
I'm trying to create an array of long in java, but eclipse is showing me an error as shown below:
Below is my code:
How can I resolve this?
Can't i create a long size array in java?
Upvotes: 25
Views: 105506
Reputation: 139
The index needs to be int so I convert long to int.
long n = sc.nextLong();
long[] arr = new long[(int)n];
Upvotes: 0
Reputation: 1
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] arr = new long[n];//Just declare the size of array of int type , because we cannot declare the size of array as long type ,rather we can store the long type in it ,This code will fix the error .
for(int i=0;i<n;i++)
{
arr[i]=sc.nextLong();
}
for(long i:arr)
{
System.out.print(i+" ");
}
}
}
Upvotes: 0
Reputation: 1
Please note that array size is always equal to int size. if you specify the array size more than 2147483647 you will get error. long n; long a[]=new long[n]; this will create error because long n exceeds 2147483647. if int n then no error occurs.
Upvotes: 0
Reputation: 533530
i need an array of 10^9 elements
You can create an array of one billion using an int
value. Make n
an int, and you can create an array with new long[n]
Note: this will use 8 GB of heap.
Since you are building all the elements using a formula, you should be able to give all the values dynamically. i.e. create a component which is a "virtual" array which would save you having to generate an array of them all.
The reason I point this out is that the second loop is likely to take minutes at best if k
is very small, or could easily take days.
BTW: I can't see all the code, but it appears you never need more than k+1
values which can be allocated once instead of n-k
times.
Upvotes: 2
Reputation: 26185
You have my sympathy. We go through this every time memory sizes increase. There is a strange expectation that this time array sizes will not need to increase in parallel with memory sizes.
Your best solution is probably to write your own class with long get(long index)
and void set(long value, long index)
methods. It could represent the data as a long[10][1000000000], and encapsulate the mapping between the natural long index and the actual pair of int indices.
Upvotes: 0
Reputation: 359836
Arrays of longs are fine: long[]
. But all arrays are int
-indexed. So just change long n
to int n
in the method parameter declaration, and you'll be all set.
Upvotes: 28