Skip to content

Instantly share code, notes, and snippets.

@flyinghyrax
Last active April 1, 2016 01:21
Show Gist options
  • Save flyinghyrax/bc3b888f9265a34ef6858cc49a105e53 to your computer and use it in GitHub Desktop.
Save flyinghyrax/bc3b888f9265a34ef6858cc49a105e53 to your computer and use it in GitHub Desktop.
Poking at anonymous inner classes
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class AnonTest {
public static void main(String[] args) {
//
System.out.printf("i\tNamed\tAnonymous%n");
for (int i = 0; i < 10; i += 1) {
// generate points
List<Point> sortMe = Point.makeRandomPoints(100000);
double avgNamedTime = Timer.averageTime(AnonTest::sortNamed, sortMe, 2);
double avgAnonTime = Timer.averageTime(AnonTest::sortAnon, sortMe, 2);
System.out.printf("%d\t%6.2f\t%6.2f%n", i, avgAnonTime, avgNamedTime);
}
}
static List<Point> sortNamed(List<Point> points) {
List<Point> copy = copyList(points);
copy.sort(new CompareX());
copy.sort(new CompareY());
return copy;
}
static List<Point> sortAnon(List<Point> points) {
List<Point> copy = copyList(points);
copy.sort(new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
int x1 = p1.x();
int x2 = p2.x();
if (x1 < x2) {
return -1;
} else if (x1 > x2) {
return 1;
} else {
return 0;
}
}
});
copy.sort(new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
int y1 = p1.y();
int y2 = p2.y();
if (y1 < y2) {
return -1;
} else if (y1 > y2) {
return 1;
} else {
return 0;
}
}
});
return copy;
}
private static <T> List<T> copyList(List<T> its) {
List<T> copyOf = new ArrayList<>(its.size());
copyOf.addAll(its);
return copyOf;
}
}
// totally normal class that implements comparator
class CompareX implements Comparator<Point> {
@Override
public int compare(Point p1, Point p2) {
int x1 = p1.x();
int x2 = p2.x();
if (x1 < x2) {
return -1;
} else if (x1 > x2) {
return 1;
} else {
return 0;
}
}
}
class CompareY implements Comparator<Point> {
@Override
public int compare(Point p1, Point p2) {
int y1 = p1.y();
int y2 = p2.y();
if (y1 < y2) {
return -1;
} else if (y1 > y2) {
return 1;
} else {
return 0;
}
}
}
i Named Anonymous
0 48.00 74.00
1 37.00 43.00
2 37.00 36.50
3 35.50 39.00
4 35.50 35.50
5 35.00 37.50
6 36.00 35.50
7 35.50 35.50
8 35.50 34.50
9 35.00 35.50
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment