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.
public void setAdjustNum(final int adjustNum)currently is pointless and does nothing because you just assign the passed argument to itself:adjustNum = adjustNum. Maybe you meantthis.adjustNum = adjustNum;but as i don't know what end result you even expect I can't tell you if this will lead to it.