Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make REALLY large boolean arrays using Java?

Tags:

java

boolean

When I try to make a very large boolean array using Java, such as:

    boolean[] isPrime1 = new boolean[600851475144];

I get a possible loss of precision error?

Is it too big?

like image 884
Miamian Avatar asked Jan 19 '09 17:01

Miamian


People also ask

What is the largest array of type boolean that you can create in Java?

The results show the maximum size is 2,147,483,645. The same behavior can be observed for byte, boolean, long, and other data types in the array, and the results are the same.

Can you have an array of booleans in Java?

The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null.

How do you create an array of booleans?

Initialize an Array of Boolean Values using for loop #const arr2 = new Array(3); for (let i = 0; i < arr2. length; i++) { arr2[i] = false; } // 👇️ [false, false, false] console. log(arr2); We used the Array() constructor to create an array of 3 empty elements, just like in the last example.

How do you set a boolean array to all false in Java?

In Java, a primitive variable has a default value. For example, a primitive int variable's default value is 0, and a primitive boolean variable will hold false by default. Therefore, if we want to initialize a boolean array with all false, we can simply create the array without setting the values.


2 Answers

To store 600 billion bits, you need an absolute minimum address space of 75 gigabytes! Good luck with that!

Even worse, the Java spec doesn't specify that a boolean array will use a single bit of memory for each element - it could (and in some cases does) use more.

In any case, I recognise that number from Project Euler #3. If it needs that much memory, you're doing it wrong...

like image 91
Alnitak Avatar answered Oct 24 '22 23:10

Alnitak


Consider using a BitSet.

like image 40
Hilton Campbell Avatar answered Oct 25 '22 00:10

Hilton Campbell