-1

For instance, I have a custom class called Boxcar, used like this:

public Boxcar(String c, int u, boolean r)

In another class, I initialize an ArrayList of Boxcars called train like this:

private ArrayList<Boxcar> train = new ArrayList<Boxcar>();

The problem I have is, I need to change String c to something else for every Boxcar in train. I imagine I need a for each loop so what I have now is:

public void setCargo(String replace)
{
    for(Boxcar b: train)
    {
        b = new Boxcar(replace);
    }
}

Which of course doesn't compile as it needs values for int u and boolean r. How can I access String c? Sorry for the noobish programming and I hope I was specific enough.

zantezuke
  • 25
  • 4

2 Answers2

1

The code in your for loop doesn't change anything in the list. It is just assigning a new car to a the local variable b (provided it called the constructor correctly), leaving the array list unchanged.

What you want is changing a value on Boxcar objects, which you would typically do with a setter:

for(Boxcar b: train) {
    b.setC(replace);
}

This assumes that your Boxcar class has getters and setters:

public Boxcar(String c, int u, boolean r){
   //constructor code
}
public getC(){
    return this.c;
}
public setC(String c){
    this.c = c;
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
0

Standard practice is to have getters/setters in your class for variables that you wish to obtain or change once you have instantiated an object of that class.

So in your Boxcar class you would have something like

public int getU() {
    return u;
}

public void setU(int newValue){
    this.u = newValue;
}

This then enables you to keep the variable u private, whilst still enabling access via these getters and setters. You can then use your for loop to cycle through your ArrayList of Boxcars and call on the setter method for the value you wish to change and do so accordingly.

As a side note I'd suggest you change your variable names of c, u and r to something more human friendly as these give no indication as to what these values mean.

Maltanis
  • 513
  • 1
  • 5
  • 13