The code for the static initializer is exceeding the 65535 bytes limit error in java?

前端 未结 3 735
孤街浪徒
孤街浪徒 2020-12-11 22:17

Hi I am trying to initialize 4 string arrays of length 10,100,1000,10000 and these arrays are like

array1={\"0\",\"1\",...\"9\"} 
array2={\"00\",\"01\",...\         


        
相关标签:
3条回答
  • 2020-12-11 22:30

    Constant array in are initialized in java bytecode by loading each value from the constant pool and assigning it to the corresponding array index. This takes several bytes of code per array element. The size of a jvm method is limited to 65535 bytes since its length is stored in the class file using a 16 bit number.

    In the case where the values can not be easily calculated in a loop, you could break the initialization into separate static functions:

    static {
        array1 = getValuesForArray1();
        ...
    }
    
    private static String[] getValuesForArray1() {
        ...
    }
    

    If there is a pattern to the initialization values its of course better to calculate the values on the fly.

    0 讨论(0)
  • 2020-12-11 22:50

    Use for loops. For example:

    for (int i = 0; i <= 9; i++)
        array1[i] = String.valueOf(i);
    
    0 讨论(0)
  • 2020-12-11 22:54

    It maybe better solved by writing a method that takes an int argument and returns the string value that would have been at that array index. Here it is using String.format and specifying the left padding length:

    private static String getValue(int index, int stringLength) {
        return String.format("%0" + stringLength + "d", index);
    }
    
    0 讨论(0)
提交回复
热议问题