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?