我有一个像这样开始的构造函数:
public Unit(String name, double[] initialPosition, int weight, int strength, int agility, int toughness,
int currentHealth, int currentStamina) {
我想写出一些测试,但要做到这一点,我需要知道将数组传递给构造函数的语法。 我在寻找构造函数之前无需定义数组就找到了这样做的方法。
答案 0 :(得分:3)
在调用构造函数(内联)时创建数组:
new Unit("myname", new double[]{1.0,2.0},...);
或重构您的构造函数以使用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 );
但是,我假设您需要一个特定数量的位置坐标,所以我不会使用数组而是使用一个对象:
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), ... );
使用数组的优点:
答案 1 :(得分:1)
调用Unit构造函数时可以使用内联参数...
Unit("String name", new double[]{0.0, 1.1, 3.3}, 0, 3, 2, 1,
2, 4) {
将是
ask n-of 40 turtles [ <whatever you want them to do> ]
这看起来像你需要的吗?
答案 2 :(得分: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.
}