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