Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Initialize an int array in a constructor

Tags:

java

I have a class and in that class I have this:

 //some code  private int[] data = new int[3];  //some code 

Then in my constructor:

public Date(){     data[0] = 0;     data[1] = 0;     data[2] = 0; } 

If I do this, everything is OK. Default data values are initialized but if I instead do this:

public Date(){     int[] data = {0,0,0}; } 

It says:

Local variable hides a field 

Why?

What's the best way to initialize an array inside the constructor?

like image 879
Favolas Avatar asked Nov 09 '11 16:11

Favolas


People also ask

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.

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 declare an array in a constructor?

An array constructor can be used to define only an ordinary array with elements that are not a row type. An array constructor cannot be used to define an associative array or an ordinary array with elements that are a row type. Such arrays can only be constructed by assigning the individual elements.

How do you initialize an entire array in Java?

We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.


2 Answers

private int[] data = new int[3]; 

This already initializes your array elements to 0. You don't need to repeat that again in the constructor.

In your constructor it should be:

data = new int[]{0, 0, 0}; 
like image 78
Bhesh Gurung Avatar answered Oct 08 '22 10:10

Bhesh Gurung


You could either do:

public class Data {     private int[] data;      public Data() {         data = new int[]{0, 0, 0};     } } 

Which initializes data in the constructor, or:

public class Data {     private int[] data = new int[]{0, 0, 0};      public Data() {         // data already initialised     } } 

Which initializes data before the code in the constructor is executed.

like image 44
pillingworth Avatar answered Oct 08 '22 10:10

pillingworth