Can you populate a List<Integer> within a user defined constructor?

Viewed 63

I'm new to Java and hoping for some advice on instantiating List<Integer> arrays within a user defined constructor.

for example:

import java.util.*;

public class Sample {

    // variables
    private List<Integer> myList = new ArrayList<>(); 
    
    // constructor
    // list of values something like (1,2,3,4,5)
    public Sample(List<Integer> listOfValues)
    {

        {
            myListArrays.addAll(Arrays.asList( listOfValues ));
        }   
    }
        
}

So my constructor call would be:

Sample s = new Sample((1,2,3,4,5));

Is it possible to do something like the above or is there an alternative approach to this type of assignment?

2 Answers

If you want to make a call like that, then you need to use varargs.

public Sample(Integer... listOfValues)
{
    myListArrays.addAll(Arrays.asList(listOfValues));
}
Sample s = new Sample(1,2,3,4,5);

See also: Varargs in Java | Baeldung

Declare without instantiating

The task is to instantiate it in the constructor, therefore you do not need to instantiate it at declaration:

private List<Integer> myList;

You can pass a parameter to the constructor

public Sample(Integer[] values) {
    myList = Arrays.asList(values)
}

Call it

Integer[] elements = {1, 2, 3, 4, 5, 6};
Sample mySample = new Sample(elements);
Related