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.
Expert's answer
First of all add to your class declaration which is
class Tutor {
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:
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;

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


for numerical values i recomend to do it this way

public intcompareTo(Tutor o) {

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!


No comments. Be the first!

Leave a comment

Ask Your question

New on Blog