我有以下内容:
public class Car{
public Car()
{//some stuff
}
private Car [] carmodels ;
public Car [] getCarModel() {
return this.carmodels;
}
public void setcarModel(Car [] carmodels ) {
this.carmodels = carmodels;
}
现在在我的测试课上,我有类似的东西
public void main (String [] args)
{
Car car1= new Car();
car.setcarModel(new Car[5]);//here i create an array of Car
for(int i =0;i<5;i++)
{
// how can i created 5 cars and set them based on index i
// car.setCarModel[new Car()]????
}
}
怎么办?我可以使用Car类型的临时数组,我可以在循环之后传递给我的Setter。但是有更好的方法吗?
答案 0 :(得分:3)
查看方法 let spots = rootRef.child("spots")
spots.observeEventType(.Value, withBlock: { snapshot in
for item in snapshot.children {
print("test")
}
})
?该方法返回 spots.observeEventType(.Value, withBlock: { snapshot in
var array:[FBAnnotation] = []
let pinTwo = FBAnnotation(name: "test", image: "test", desc: "test", longitude: 57.18506643076407, latitude: 9.78643024224879)
array.append(pinTwo!)
let pinOne = FBAnnotation(name: "test", image: "test", desc: "test", longitude: 57.18506643076407, latitude: 9.78643024224879)
array.append(pinOne!)
self.clusteringManager.addAnnotations(array)
})
对吗?这意味着您可以在getCarModel
上的数组上执行任何操作!
那么如何在数组的索引处设置项?你这样做:
Car[]
如果我们将此应用于car1.getCarModel()
返回的数组,
someArray[someIndex] = someValue;
这是做到这一点的方法。
或者,您可以在car1.getCarModel
中编写另一种方法来设置汽车模型数组中的项目:
car1.getCarModel()[i] = new Car();
简单!
不过,你的模型毫无意义......答案 1 :(得分:2)
如果你坚持不在for循环中使用临时值,你可以使用ArrayList而不是数组来表示carmodels。
而不是添加方法
public void addCar(Car toadd)
{
carmodels.add(toadd);
}
比你的foor循环中只需要调用
for(int i =0;i<5;i++)
{
car.addCar(new Car());
}
我假设大小可能会有所不同,并且固定大小的数组是不够的。
答案 2 :(得分:1)
for(int i =0;i<5;i++)
{
car.getCarModel()[i] =new Car();
}
或
通过传递索引来编写另一个重载的setter。
public void setCarModel(int index, Car c)
{
carmodels[index] = c;
}
for(int i =0;i<5;i++)
{
car.setCarModel(i, new Car());
}
答案 3 :(得分:1)
添加一个接受索引的setter:
public void setCarModel(int index, Car carModel) {
this.cardmodels[index] = carModel;
}
然后,在你的循环中,调用
car.setCarModel(i, new Car());