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;
Comments
Leave a comment