Reputation: 147
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);
}
}
Upvotes: 0
Views: 361
Reputation: 22038
You'd better use the IComparable<>
interface.
"The object to be sorted will implement IComparable while the class that is going to sort the objects will implement IComparer."
Source: difference between IComparable and IComparer
public class Point : IComparable<Point>
{
public int x;
public int y;
public Point(int x_Point, int y_Point)
{
x = x_Point;
y = y_Point;
}
public int CompareTo(Point other)
{
if (this.x == other.x && this.y == other.y)
return 0;
if (this.y < other.y)
return -1;
if (this.y == other.y && this.x < other.x)
return -1;
return 1;
}
}
public static void Main()
{
var AL = new List<Point>(); // ditch the ArrayList for good... ;-)
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);
}
Upvotes: 2