Answer to Question #26971 in Java | JSP | JSF for Brad Jones

Question #26971
I am using a Class (Named Tutor) outside of my main, while I am able to put a First and Last name into an Array and print them back out, when i try to sort the Array using Arrays.sort(nameOfArray); I get the exception Exception in thread "main" java.lang.ClassCastException: Tutor cannot be cast to java.lang.Comparable. I Want to try and sort all names by Last name in the Array.
1
Expert's answer
2013-03-25T12:55:37-0400
First of all add to your class declaration which is
class Tutor {
//code
}
now add the 'implements comparable' string so it willlook like this


import java.lang.Comparable;

class Tutor implements Comparable<Tutor> { //yourcode here }

The last but not the least:
add
public int compareTo(Tutor o)
{
}
method which returns integer values in logic like these:
if (this>o) return 1 (or more)
if (this==o) return 0
if (this<o)return -1 (or less)

Almost all types are comparable, so you may try somethinglike this


public class Tutor implements Comparable<Tutor> {private String name;

@Override
public intcompareTo(Tutor o) {
// willsort tutors alphabeticaly
return name.compareTo(o.name);
}

}

for numerical values i recomend to do it this way

@Override
public intcompareTo(Tutor o) {
returnthis.numerical-o.getNumerical;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS