How do I sort a List of Points by using an customized compare method?
using System;
using System.Collections;
using System.Collections.Generic;
public class Point : IComparer<Point>
{
public int x;
public int y;
public Point(int x_Point, int y_Point)
{
x = x_Point;
y = y_Point;
}
public int Compare(Point a, Point b)
{
if (a.x == b.x && a.y == b.y)
return 0;
if (a.y < b.y)
return -1;
if (a.y == b.y && a.x < b.x)
return -1;
return 1;
}
}
The code below throws an error at AL.sort().
"Failed to compare two elements in the array." "ArgumentException: At least one object must implement IComparable"
I have no clue why. Did I described my own comparing method at the Points class wrong?
public class ArrayListTest
{
public static void Main(string[] args)
{
ArrayList AL = new ArrayList();
Random R = new Random();
for (int i = 0; i < 10; i++)
{
Point p = new Point(R.Next(50), R.Next(50));
AL.Add(p);
}
PrintValues(AL);
AL.Sort();
PrintValues(AL);
}
}
ArrayListinstead useList<Point>.ArrayListis a left over from the dark days before generics. Also you should be implementingIComparableinstead ofICompareras the former is to indicate that the type can compared to other instances of the same type and the later just indicates that it can compare two instances of a given type.