Simonas
Simonas

Reputation:

ArrayList object sorting

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

Upvotes: 1

Views: 906

Answers (2)

Michael Borgwardt
Michael Borgwardt

Reputation: 346270

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

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421978

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

Upvotes: 2

Related Questions