2016-02-29 77 views
0

我启动这样一个构造函数:我想写一些测试试图传递一个数组构造

public Unit(String name, double[] initialPosition, int weight, int strength, int agility, int toughness, 
     int currentHealth, int currentStamina) { 

,但要做到这一点,我需要知道的语法来传递一个数组构造函数。 我正在寻找一种方法来做到这一点,而不必在我调用构造函数之前定义数组。

+2

如果你不想让你调用构造函数之前定义的数组,那么为什么使它成为一个参数?你总是可以重载构造函数 - 或者创建另一个不使用数组作为参数的构造函数。 –

回答

3

要么调用构造函数(在线)时创建数组:

new Unit("myname", new double[]{1.0,2.0},...); 

或调整你的构造函数使用可变参数:

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); 

不过,我认为你需要坐标的特定号码位置,所以我不会使用阵列,但一个对象为:

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), ...); 

使用阵列的优点:

  • 它是类型安全的,即您传递位置而不是任意的双精度数组。这样可以防止您偶然在其他阵列中传递的错误。
  • 它定义了编译时的坐标数,即你知道一个位置的坐标数(在我的例子中是2),而当使用一个数组(或可变参数基本相同)时,你可以传递任意数量的坐标( 0到Integer.MAX_VALUE)。
1

调用构造单元时,您可以使用内联参数...

例子:

Unit(String name, double[] initialPosition, int weight, int strength, int agility, int toughness, 
     int currentHealth, int currentStamina) { 

Unit("String name", new double[]{0.0, 1.1, 3.3}, 0, 3, 2, 1, 
     2, 4) { 

这是否看起来像你需要什么???

+0

谢谢你的答案,但我接受了托马斯的答案,因为它说的相同,但也给出了更多的选择 – Sander

0

当您将数组传递给任何方法或构造函数时,将传递其引用的值。参考意味着地址..

一个例子: 类: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. 
} 
+0

这不适合“我正在寻找一种方法来做到这一点,而不必在我调用构造函数之前定义数组“。 – Thomas

+0

@Thomas编辑它。 –

+0

这不会使IMO更好。您现在定义一个全为空的5个元素的数组。我猜想OP想传递一些值而不是在构造函数中创建它们。 – Thomas