I'm abstracting some things in a class and therefore want to pass different class variables (fields) to the same method and have them incremented. I'm finding that the field does not get modified even though I'm passing it into the method.
I have the following simplified code. First the line that initiates the class variable/field, then the constructor that calls the method, then the method.
public class Demo {
public Integer countOfOnlyOneSameInTop12 = 0;
Demo() {
summarize(countOfOnlyOneSameInTop12);
}
private void summarize(Integer countOfOnlyOneSameInTop12) {
countOfOnlyOneSameInTop12++;
countOfOnlyOneSameInTop12++;
countOfOnlyOneSameInTop12++;
System.out.println(countOfOnlyOneSameInTop12); // 3
}
public static void main(String[] args) {
Demo demo = new Demo();
System.out.println(demo.countOfOnlyOneSameInTop12); // 0
}
}
When I step through, I expect to see countOfOnlyOneSameInTop12 incremented at the class level because it is passed into the method by the calling line of code. However the value of the class variable/field does not change even though the value of the variable inside the method does increment by one.
According to the experts then, this is a pass-by-value problem.
My question then, is how do I get around it? I want to add to the value of a class variable inside a method and I want to abstract that class variable/field in order to run several through the same method.
Do I need a class wrapper for the Integer?
Am I taking the wrong approach? Incrementing a class-level counter seems reasonable.
The only alternative I see to trying this in some form is a bunch of code duplication.
See my comment below for how a worked around the Integer problem.