How do i sort ?

G

gk

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.
 
T

Tor Iver Wilhelmsen

gk said:
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().
 
T

Tom Cole

gk said:
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.

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.
 
T

Tomasz Lewandowski

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
}
}
}

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,078
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top