0

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?

1 Answer 1

1

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.

3
  • Thanks for this. I was thinking I'd have to pass it in as an array but this structure automates that exactly the way I was looking for~ "SetOfDice(int numDice, int... values)" Am I right in thinking what this would do is create a values[] array from the arguments list that I can reference with values[0], values[1], etc?
    – ShilohPell
    Commented Sep 21, 2017 at 5:32
  • @ShilohPell Yes, exactly. values gets turned into an array representing the arbitrary number of integers passed. you could simply assign your dice class member to values rather than copy them since the array does not exist outside of your constructor and int value types cannot be reassigned.
    – Neil
    Commented Sep 21, 2017 at 7:22
  • @Hangman4358 No need to pass numDice to the constructor since the number of dice can be determined by values.length. No point duplicating data.
    – Neil
    Commented Sep 21, 2017 at 7:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.