Question: I have the following:

```
public class  Car{
public Car()
{//some stuff
}
private Car [] carmodels  ;
public Car [] getCarModel() {
return this.carmodels;
}

public void setcarModel(Car [] carmodels ) {
this.carmodels = carmodels;

}

```

Now on my test class, I have something like this

```
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()]????
   }
 }

```

How can do that? I could use a temp array of type Car which I can pass to my Setter just after the loop. But is there a better way?

Answer: 
If you insist on not using a temp value in the for loop you could use an [ArrayList](https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html) instead of an array for the carmodels.

than add a method

```
public void addCar(Car toadd)
{
     carmodels.add(toadd);
}

```

than in your foor loop just call

```
for(int i =0;i<5;i++)
{
    car.addCar(new Car());
 }

```

Im assuming the size can vary and that a fixed size array is not sufficient.
```
for(int i =0;i<5;i++)
{
  car.getCarModel()[i] =new Car();
}

```

or

Write another overloaded setter by passing index.

```
public void setCarModel(int index, Car c)
{
 carmodels[index] = c;
}

for(int i =0;i<5;i++)
{
   car.setCarModel(i, new Car());
}

```