1

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
1
  • PascalCase Sort is a clue it's C# and not Java. Commented Apr 29, 2010 at 7:37

2 Answers 2

2
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());
Sign up to request clarification or add additional context in comments.

3 Comments

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?
public class IdComparer implements Comparator<MyObjectType> { appears to be ok, but I'd still like to understand your syntax. Thanks
@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#.
1

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.