Search code examples
javaanonymous-class

Why updating a primitive instance variable value referring by the method of an anonymous class does not update the value in the method of it?


Here is a problem I face when maintaining and old application, below are the code for demonstration: First, I created a class with field innerComp valued by instance of an anonymous class and a field adjustNum which is used in a method of innerComp:

public class InnerComparator {
private int adjustNum = 0;

public InnerComparator() {

}

public InnerComparator(int adjustNum) {
    this.adjustNum = adjustNum;
}

public void setAdjustNum(int adjustNum) {
  //        adjustNum = adjustNum;
      this.adjustNum = adjustNum;
}
private Comparator innerComp = new Comparator() {
    @Override
    public int compare(Object o1, Object o2) {
        System.out.println(adjustNum);
        return adjustNum;
    }
};

public Comparator getInnerComp() {
    return innerComp;
}

public void sort(List list) {
    Collections.sort(list, innerComp);
}

}

Here demonstrate how I use it:

public class CheckInnerClassUpdate {
public static void main(String[] args) {
    InnerComparator comparator = new InnerComparator();
    List<String> list = Arrays.asList(new String[]{"1", "2", "3"});
    comparator.sort(list);
    comparator.setAdjustNum(1);
    comparator.sort(list);
    InnerComparator comparator2 = new InnerComparator(1);
    // comparator.sort(list);
    comparator2.sort(list);
}

}

The result is: 0 0 1 1 1 1

(Obsolete) The result is: 0 0 0 0 0 0 I would like to ask for the mechanism that generate the result. The result seems show that the adjustNum pass to the instance of the anonymous class is referring to the init value of the adjustNum. In the sample code, even if I pass the value via the constructor, the value pass to the innerComp is still 0. There is a missing piece of knowledge that I don't know and hopefully someone could help. Thank you.

(Updated) As mentioned answer, typo cause the confusion. I have fix the code and comment out the original code.


Solution

  • I found at least an error in your code:

    public void setAdjustNum(int adjustNum) {
        adjustNum = adjustNum;
    }
    

    This method does nothing because it resets adjustNum passed as parameter to the function. If you need to set the adjustNum field of the class your code must be updated to

    public void setAdjustNum(int adjustNum) {
        this.adjustNum = adjustNum;
    }
    

    So the this.adjustNum refers to the property of the instance, while adjustNum (without this) refers to the parameter passed to the function. In this case you really set the adjustNum calling setAdjustNum method