I have a class.
the class has member variables String StudentName , String MobleNumber.
I have created 4 objects of this class.
Now,i want to sort these objects (based upon alphabetical StudentName
).
How do i sort ?
can i use Collection.sort() here.
can you suggest an easy way to sort the objects.
> can i use Collection.sort() here.
Yes, if:
1) your bean class implements Comaparable and you implement
compareTo() right, or
2) you create a Comparator class and send an instance of that as the
second argument to sort().
> I have a class.
> the class has member variables String StudentName , String MobleNumber.
[quoted text clipped - 9 lines]
>
> can you suggest an easy way to sort the objects.
Depends on how you want them sorted and if you allow nulls.
Here we'll assume you don't allow nulls and you want Students sorted
by name, then number.
public class Student implements Comparable {
private String studentName = null;
private String mobileNumber = null;
public Student(String name, String number) throws
NullPointerException {
//we hate nulls so we won't allow them. You can change this of
course...
if (name == null || number == null) {
throw new NullPointerException("Student instances requires a
valid name and number parameter");
}
else {
this.studentName = name;
this.mobileNumber = number;
}
}
...
public int compareTo(Object o) throws ClassCastException {
Student other = (Student) o;
int comp = this.studentName.compareTo(other.studentName);
if (comp == 0) {
return this.mobileNumber.compareTo(other.mobileNumber);
}
else {
return comp
}
}
}
HTH.
Tomasz Lewandowski - 17 Sep 2006 09:24 GMT
> public int compareTo(Object o) throws ClassCastException {
> Student other = (Student) o;
[quoted text clipped - 7 lines]
> }
> }
It may fail if students have non-english names, because String's compareTo
implementation sorts strings using unicode character codes, not national
char sequence. If this is the case then you should use java.text.Collator
class.