Re: sorting an ArrayList<Points> by x or y value
- From: Knute Johnson <nospam@xxxxxxxxxxxxxxxxx>
- Date: Thu, 16 Mar 2006 18:19:31 -0800
emmoore wrote:
Hello everybody. I am rather new to Java, and I'm struggling understanding a
program I have to write that needs to use a Comparator. I really don't
understand how to use one or where to put it.
My task is to write a method sort(d) that will sort an ArrayList of points by
x value if d=0 and by y value if d=1. I think I've managed to create the
ArrayList of points needed, but I feel as if I've hit a complete impasse when
it comes to figuring out how to sort in the necessary way.
I've tried doing this a few different ways, all of which are wrong, but maybe
you might help steer me in the correct direction.
One try:
public static ArrayList<Point> sort(final int d)
{ Comparator MyLittlePointComparator = new Comparator() {
public int compare(Object o1, Object o2) {
return compare( (Point)o1, (Point)o2);
}
public int compare(Point p, Point q) {
int diff;
if (d==0)
diff = p.x - q.x;
else if (d==1)
diff = p.y - q.y;
return diff;
} }
return Collections.sort(this_use_array, MyLittlePointComparator());
Another try:
public static ArrayList<Point> sort(final int d)
{
public class MyLittlePointComparator extends PS7File.EqComparator
implements Comparator<Point>
{
public int compare(Point p, Point q)
{
if (d == 0)
{
double pee = p.getX();
double kyew = q.getX();
}
else if (d == 1)
{
double pee = p.getY();
double kyew = q.getY();
}
if (pee < kyew) return -1;
if (pee == kyew) return 0;
return 1;
}
}
return Collections.sort(this_use_array, new MyLittlePointComparator());
}
}
I just have no idea where to even begin fixing this. The task seems so simple
(just sorting by x and y value), but I feel so lost. Thanks so much in
advance for your time and help.
You need to read the docs on Comparator very closely. The procedure in a nutshell is to create a Comparator that will compare your Points by the values. Then all you have to do is call Collections.sort(yourList, yourComparator). Look at the Collections docs too.
--
Knute Johnson
email s/nospam/knute/
.
- References:
- sorting an ArrayList<Points> by x or y value
- From: emmoore
- sorting an ArrayList<Points> by x or y value
- Prev by Date: decimal format, how to not round
- Next by Date: Re: sorting an ArrayList<Points> by x or y value
- Previous by thread: sorting an ArrayList<Points> by x or y value
- Next by thread: Re: sorting an ArrayList<Points> by x or y value
- Index(es):
Relevant Pages
|