How to make a big array in java

后端 未结 5 672
抹茶落季
抹茶落季 2020-12-20 17:44

I want to create a boolean array of a size which the user is going to put as input.For example - The user might put a big number like 1000000000000 ; so then I have to creat

5条回答
  •  暖寄归人
    2020-12-20 18:05

    You could create an abstraction, for example array of arrays (you can even modify this).

    Object [][] can be boolean or whatever.

    class LargeArray {
    
        private final long size;
        private final int sizeI;
        private final int sizeJ;
        private final Object [][] objects;
    
    
        public LargeArray() {
            sizeI = 3;//Any reasonable value;
            sizeJ = Integer.MAX_VALUE;
            objects = new Object [sizeI][sizeJ];
            size = sizeI * sizeJ;
        }
    
        public long size() {
            return size;
        }
    
        public Object get(long index) {
             int i = index / sizeJ;
             int j = index % sizeJ;
             return objects[i][j];
        }
    
        public void set(long index, Object object) {
             int i = index / sizeJ;
             int j = index % sizeJ;
             objects[i][j] = object;
        }
    }
    

    You could also change first dimension, say 3. In this case Object [3][Integer.MAX_VALUE], you can create (2^31 -1)*3 = 2,147,483,647 * 3 = 6442450941 elements and you will need (2^31 - 1)*3 * 4 =~ 23 GB RAM, which is actually possible!!!:)

提交回复
热议问题