Anonymous classes are turned into a regular class definition by the compiler and are actually given a name like OutterClass$1
, you can not refer to that class by that name but you can do for example new Object() {}.class.getName()
to see that it's always the same. Whenever your code hits the line in question it's using just 1 class - whether you give it an explicit name or not. Your 2 options are basically the same.
But when you read your line of code up until Collections.sort(originalList, new
you should be aware that that new
creates a new instance (not a class) every time. I.e. it allocates memory, initializes the thing, .. none of which is needed more than once because the created comparator object will never differ.
What you'll want to do is either storing the created comparator once in a field like so (or like in Java's own source String.CASE_INSENSITIVE_ORDER
)
private static final Comparator<User> USER_COMPARATOR = new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
int value1 = o1.getPropertyCode().compareTo(o2.getPropertyCode());
if (value1 == 0) {
int value2=o1.getPropertyValue().compareTo(o2.getPropertyValue());
return value2;
}
return value1;
}
};
private void someCode() {
Collections.sort(originalList, USER_COMPARATOR);
}
Or with Java 8 you can turn it into a lambda (notice the missing new
) which also doesn't create new instances every time
Collections.sort(originalList, (o1, o2) -> {
int value1 = o1.getPropertyCode().compareTo(o2.getPropertyCode());
if (value1 == 0) {
int value2=o1.getPropertyValue().compareTo(o2.getPropertyValue());
return value2;
}
return value1;
});