简体   繁体   中英

are these two Java arrays identical?

Are these two arrays identical in form? (They seem to be when tested.) If yes, then why are they both permitted? Is one purely for backward compatibility? Which is best practice?

public static void main(String[] args)
{
    Auto[] array0 = new Auto[] { new Auto(6, "Lemons"),
                                 new Auto(4, "Rusty")
                               };

    Auto[] array1 = { new Auto(5, "German"),
                      new Auto(8, "Detroit") 
                    };
}

The latter can only be used to initialize an array when you are declaring it.

For example, suppose you have the following method:

public void foo(Auto[] autos) {
}

In this case, you could do foo( new Auto[] { new Auto(6, "Lemons") }) , but not foo( { new Auto(6, "Lemons") }) .

They are equivalent.

However, the second syntax can only be used when you are initializing variables (where the compiler can infer the type). So the first syntax is useful for situations where you want to create a temporary, eg:

void foo(Auto[] stuff) {
    ...
}


foo(new Auto[] { new Auto(6, "Lemons"), new Auto(4, "Rusty") });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM