1

I was wondering how do i initialize numdata in my default constructor. Do I set the length? I basically need help understanding the default process in initializing an integer array in a class constructor.

public class Numbers 
{
    private int [] numdata;

    public Numbers()
    {
        numdata = 
    }


}
kay
  • 356
  • 1
  • 4
  • 18
  • 3
    See: http://stackoverflow.com/questions/1938101/how-to-initialize-an-array-in-java or https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html – Aracurunir Nov 22 '15 at 20:49

2 Answers2

1

If you have at least a rough idea of the size of the array you wish to create, then it's straight forward. You can instantiate a new array in the constructor for that size and live with it.

A good programming practice would be to create a final variable for the array size and use it to create the array.

However, if you wish to create a resizeable array, you should be looking at the Collections framework.

For beginner purposes, the following should do.

public class Numbers {
    private int[] numdata;
    private static final MAX_SIZE = 100;

    public Numbers(){
        numdata = new int[MAX_SIZE];
    }    
}
Sarath Chandra
  • 1,850
  • 19
  • 40
0

If you want to initialize the array with data do it this way:

numdata = new int[]{1, 2, 3, 4};

This will create an array of length 4. If you do not have the content, but only the length of the array do it this way:

numdata = new int[4];

Howevever if you do not know how many elements there might be you should use a list instead:

public class Numbers 
{
    private List<Integer> numdata;

    public Numbers()
    {
        numdata = new ArrayList<Integer>();
    }
}
hotzst
  • 7,238
  • 9
  • 41
  • 64