63 076
Assignments Done
99,1%
Successfully Done
In July 2018

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 {
//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 first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions