2

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 = 
    }


}
1

2 Answers 2

2

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];
    }    
}
Sign up to request clarification or add additional context in comments.

Comments

1

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>();
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.