In a different post, I was told that it is wrong to define an anonymous inner class “after” (below) a function which uses it. However, something like the below compiles and runs fine:
public class CompTest {
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<Integer>(intComp);
ts.add(1);
ts.add(2);
ts.add(3);
System.out.println(ts.toString());
}
private static Comparator<Integer> intComp = new Comparator<Integer>() {
@Override
public int compare(Integer i1, Integer i2) {
return i2.compareTo(i1);
}
};
}
What is the official word on this? My guess is that since intComp is static, then it is instantiated once when the class CompTest is “loaded” (not sure exactly how that load takes place since there is only a main method and no CompTest objects are constructed), and therefore when main() needs intComp, it is available regardless of where in the source file it was actually defined.
And even though it does work (for the above reason or even a different one)… is it bad practice?
You are refering to this comment I believe:
There is no technical reason to put the
intCompdeclaration before (or after) themaindeclaration. It works fine either way.The only possible reason for putting the comparator earlier is stylistic. That is, the
intCompdeclaration is a static variable, and it is conventional to declare variables at the start of a class.I’m inclined agree with the style point, but it is a minor issue. Also, if it was me, I’d declare the comparator as
final, give it a more meaningful name, and use the “constant” naming style; e.g.INT_COMP(but more meaningful).Re Nambari’s comment:
This is nonsense. It is quite common for anonymous classes to be used in this way. Sure, anonymous classes can also be used in nested scopes … and that is one of their advantages … but that in no way means that this pattern is wrong.