Sander
Sander

Reputation: 152

trying to pass an array in a constructor

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

Answers (3)

Mathews Mathai
Mathews Mathai

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

Thomas
Thomas

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:

  • It is typesafe, i.e. you pass in positions and not some arbitrary array of doubles. This prevents bugs where you accidentially pass in some other array.
  • It defines the number of coordinates at compiletime, i.e. you know the number of coordinate a position has (2 in my example) whereas when using an array (or varargs which is basically the same) you could pass any number of coordinates (0 to Integer.MAX_VALUE).

Upvotes: 3

You can use inline parameters when calling the Unit constructor...

Example:

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

Related Questions