I now have the problem that I would like to sort a list. It is an Arraylist<PatientInfo> with the class PatientInfo looking like this:
I would like to sort the list by name. Is that possible? Collection.sort doesn"t work, because PateitnInfo is not per se sortable. I could write a method that sorts by name, I just want to know if there is an easier way, thanks.
The problem people have in trying to create something foolproof is that they generally underestimate the inginuity of fools.
The compareTo API says :
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
You want to sort by the name of the patient. The name is a String. String is Comparable, so you can use its compareTo method to compare the name of two patients. Try to figure out how.
Martin Vietor wrote:public class PatientInfo() implements Comparable
That should be You want its instances to be comparable to other instances, and that's what the generic part does. It then requires you to have the following method:
Without the generics the parameter type would be Object and you would need to cast it to PatientInfo.
As for the implementation, Christophe has already told you how to do it. Simply delegate the comparison to name comparison. Just one thing to think about: do you want to search case insensitively or not? If so, String has a second comparison method for this.
Well thanks, here we go. I'll try to figure it out. I'm sort of a self taught "programmer", so some terms are very abstract to me. But it's always better to read up on that oneself than getting the code done by someone else, I think.