Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I lazy-initialize static long array like this in java?

private static final long[] reservedFromIps;

static {
    reservedFromIps = {0l, 167772160l, 1681915904l, 
        2130706432l, 2851995648l, 2886729728l, 3221225984l, 3227017984l, 3232235520l, 
        3323068416l, 3325256704l, 3405803776l, 3758096384l, 4026531840l, 4294967295l}; 
}

The error is "illegal start of an expression, not a statement, ; expected"

whereas the following works fine :

private static final long[] reservedFromIps = {0l, 167772160l, 1681915904l, 
    2130706432l, 2851995648l, 2886729728l, 3221225984l, 3227017984l, 3232235520l, 
    3323068416l, 3325256704l, 3405803776l, 3758096384l, 4026531840l, 4294967295l}; 
like image 786
user1364534 Avatar asked Jan 16 '23 13:01

user1364534


2 Answers

This has nothing to do with static blocks, array constants can only be used in initializers. It's just how the language is specified.
This code wont compile either:

public class Test {
    public static void main(String[] args) {
        long[] reservedFromIps;
        reservedFromIps = {0l, 167772160l, 1681915904l, 
                2130706432l, 2851995648l, 2886729728l, 3221225984l, 3227017984l, 3232235520l, 
                3323068416l, 3325256704l, 3405803776l, 3758096384l, 4026531840l, 4294967295l}; 
    }
}

Why this is the case is probably a question of added complexity for the compiler with little added gain, but to be entirely sure you would have to take it up with the Java design team.

like image 177
Keppil Avatar answered Feb 28 '23 02:02

Keppil


Firstly there's a typo in your static initializer block (or in your field declaration). Secondly you'll have to do this:

static {
        reservedFromIps = new long[]{0l, 167772160l, 1681915904l, 
            2130706432l, 2851995648l, 2886729728l, 3221225984l, 3227017984l, 3232235520l, 
            3323068416l, 3325256704l, 3405803776l, 3758096384l, 4026531840l, 4294967295l}; 
}

Array constants can only be used in initializers, and not when reassigning an array.

like image 38
arshajii Avatar answered Feb 28 '23 04:02

arshajii