Reputation:
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
Reputation: 346270
Assuming that this is Java:
ItemIdQuantity
class implements Comparable
based on the ID field, use Collections.sort()
with the list as single parameter.Comparator
that compares the objects using their ID, and use it as second paramter to Collections.sort()
.Upvotes: 1
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