Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you use shorthand array initialization of fields in Java constructors?

Tags:

Take the following example:

private int[] list;  public Listing() {     // Why can't I do this?     list = {4, 5, 6, 7, 8};      // I have to do this:     int[] contents = {4, 5, 6, 7, 8};     list = contents; } 

Why can't I use shorthand initialization? The only way I can think of getting around this is making another array and setting list to that array.

like image 284
Ethan Turkeltaub Avatar asked Nov 28 '11 20:11

Ethan Turkeltaub


People also ask

Can an array be initialized in a constructor?

Initialize Array in Constructor in JavaWe can create an array in constructor as well to avoid the two-step process of declaration and initialization. It will do the task in a single statement. See, in this example, we created an array inside the constructor and accessed it simultaneously to display the array elements.

How do you initialize an array in a constructor in Java?

One way to initialize the array of objects is by using the constructors. When you create actual objects, you can assign initial values to each of the objects by passing values to the constructor. You can also have a separate member method in a class that will assign data to the objects.

How do you initialize a field array in Java?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

How do you initialize a string array in a constructor?

In Java, it is completely legal to initialize a String array in the following way: String[] s = {"FOO", "BAR"}; However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed: Test t = new Test({"test"});


2 Answers

When you define the array on the definition line, it assumes it know what the type will be so the new int[] is redundant. However when you use assignment it doesn't assume it know the type of the array so you have specify it.

Certainly other languages don't have a problem with this, but in Java the difference is whether you are defining and initialising the fields/variable on the same line.

like image 188
Peter Lawrey Avatar answered Oct 24 '22 02:10

Peter Lawrey


Try list = new int[]{4, 5, 6, 7, 8};.

like image 26
ziesemer Avatar answered Oct 24 '22 01:10

ziesemer