Java – Object constructors with dynamic parameter lists

constructorsjavamethodsobjectparameters

I had a quick question and I was hoping someone could help me figure this out. I'm new to Java and I'm trying to learn about classes and objects and I see you can call parameters in the constructor of the class. Such as:

public class PairOfDice {
    public int[] dice = new int[2];     //Create an array of length 2 to hold the value of each die
    PairOfDice(int die1, int die2){     //Constructor
        dice[0] = die1;                 //Assign first parameter to the first die
        dice[1] = die2;                 //Assign second parameter to the second die
    }
}

But I'm wondering if it's at all possible to tell a constructor (or any method for that matter) to expect an arbitrary number of parameters. Such as:

public class SetOfDice {
    SetOfDice(int numberOfDice /*Further parameters*/){     //Constructor
        public int[] dice = new int[numberOfDice];          //Create an array with a length based on the value of the first parameter
        for(int counter = 0; counter < numberOfDice ; counter++) {
            //Insert loop here for populating array with the rest of the parameters
        }
    }
}

I'm guessing its not but I want to be sure. Can anyone give me some insight on whether something like this is possible? And if not, let me know if there's a better means to go about getting this result?

Best Answer

What you are looking for in Java is called 'varargs' (https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html)

For your example you would probably want your constructor signature to be

SetOfDice(int numDice, int... values)

Then you probably want some sort of sanity check to make sure that the number of dice equals the length of the values array. A vararg parameter is just treated as an array of said type.

Then just copy the contents of the array into a new copy.

Sorry for the lack of linking, I have no clue how to format from my phone.