Reputation: 152
I got a constructor that starts like this:
public Unit(String name, double[] initialPosition, int weight, int strength, int agility, int toughness,
int currentHealth, int currentStamina) {
I want to write out some tests, but to do that I need to know the syntax to pass an array to the constructor. I looking for a way to do this without having to define the array before I call the constructor.
Upvotes: 0
Views: 53
Reputation: 1707
When you pass an array to any method or constructor, the value of it's reference is passed. Reference means address..
An example:
Class: Unit
Double carray[]; //class variable (array)
Unit(Double[] array) //constructor
{
this.carray=array;
this.carray={3.145,4.12345.....};
//passing an array means, you are actually passing the value of it's reference.
//In this case, `carray` of the object ob points to the same reference as the one passed
}
public static void main(String[] args)
{
Double[] arr=new Double[5];
Unit ob=new Unit(arr);
//passes `reference` or `address` of arr to the constructor.
}
Upvotes: 0
Reputation: 88757
Either create the array when calling the constructor (inline):
new Unit("myname", new double[]{1.0,2.0},...);
or restructure your constructor to use varargs:
public Unit(String name, int weight, int strength, int agility, int toughness,
int currentHealth, int currentStamina, double... initialPosition) { ... }
//call
new Unit("myname", w,s,a,t,c,stam, 1.0, 2.0 );
However, I assume you need a specific number of coordinates for the position so I'd not use an array but an object for that:
class Position {
double x;
double y;
Position( x, y ) {
this.x = x;
this.y = y;
}
}
public Unit(String name, Position initialPosition, int weight, int strength, int agility, int toughness,
int currentHealth, int currentStamina ) { ... }
//call:
new Unit( "myname", new Position(1.0, 2.0), ... );
Advantages over using an array:
Upvotes: 3
Reputation: 48297
You can use inline parameters when calling the Unit constructor...
Unit(String name, double[] initialPosition, int weight, int strength, int agility, int toughness,
int currentHealth, int currentStamina) {
will be
Unit("String name", new double[]{0.0, 1.1, 3.3}, 0, 3, 2, 1,
2, 4) {
Does this look like what you need???
Upvotes: 1