Java Initialize an int array in a constructor
To initialize an int
array in a constructor in Java, you can use an initializer list as follows:
public class MyClass {
private int[] arr;
public MyClass(int size) {
arr = new int[size];
}
}
This creates an int
array with the specified size and assigns it to the arr
field.
You can also use an initializer list to give the array an initial set of values:
public class MyClass {
private int[] arr;
public MyClass(int... values) {
arr = new int[] {values};
}
}
This creates an int
array with the same size as the values
array and copies the values from values
into the new array.
You can then use the array in your class as follows:
MyClass obj = new MyClass(1, 2, 3, 4, 5);
int[] arr = obj.getArr();
This creates a new MyClass
object with an int
array containing the values 1
, 2
, 3
, 4
, and 5
, and assigns it to the arr
field. You can access the array using the getArr
method.
Note that in this example, the int
array is marked as private, which means that it can only be accessed within the MyClass
class. If you want to be able to access the array from other classes, you will need to make it public or provide a getter method.