views:

249

answers:

2

Hi, I have to sort ArrayList which consists of objects. Object: ID, Quantity. The ArrayList should be sorted by ID. How to implement this?

ItemIdQuantity = new ItemIdQuantity (ID, Quantity);

ItemIdQuantity.Sort(); // where must be sorting by ID
+2  A: 
public class IdComparer : IComparer  {
  int IComparer.Compare(object x, object y) {
      return Compare((ItemIdQuantity)x, (ItemIdQuantity)y);
  }
  public int Compare(ItemIdQuantity x, ItemIdQuantity y) {
      return x.ID - y.ID;
  }
}

arrayList.Sort(new IdComparer());
Mehrdad Afshari
I put the first line of your code in to a new class in Eclipse and it first complains about ':' saying it expected extends, and then when I put that in, it complained IComparer cannot be resolved to a type. Where am I going wrong?
Mark Lewis
`public class IdComparer implements Comparator<MyObjectType> {` appears to be ok, but I'd still like to understand your syntax. Thanks
Mark Lewis
@Mark: The original version of the question did not have the Java tag. Apparently, a third party has added such a tag. I answered assuming the language is C#.
Mehrdad Afshari
+1  A: 

Assuming that this is Java:

  • If the ItemIdQuantity class implements Comparable based on the ID field, use Collections.sort() with the list as single parameter.
  • Otherwise, implement a Comparator that compares the objects using their ID, and use it as second paramter to Collections.sort().
Michael Borgwardt