user3841581
user3841581

Reputation: 2747

Setters based on array Index in Java

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?

Upvotes: 0

Views: 1238

Answers (4)

Sweeper
Sweeper

Reputation: 272770

See the method getCarModel? That method returns a Car[] right? That means you can do anything you can do on an array on car1.getCarModel()!

So how do you set an item at an index of an array? You do this:

someArray[someIndex] = someValue;

If we apply this to the array returned by car1.getCarModel,

car1.getCarModel()[i] = new Car();

That's the way to do it.

Alternatively, you ca write another method in Car that sets an item in the car models array:

public void setItemInCarModels(int index, Car item) {
    carModels[index] = item;
}

Simple!

Btw, your model makes no sense...

Upvotes: 3

shmosel
shmosel

Reputation: 50726

Add a setter that accepts an index:

public void setCarModel(int index, Car carModel) {
    this.cardmodels[index] = carModel;
}

Then, inside your loop, call

car.setCarModel(i, new Car());

Upvotes: 1

Sven van den Boogaart
Sven van den Boogaart

Reputation: 12325

If you insist on not using a temp value in the for loop you could use an ArrayList 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.

Upvotes: 2

Munesh
Munesh

Reputation: 1569

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

Upvotes: 1

Related Questions