Reputation:
code of the linked list
class Link
{
public Object data;
public Link next;
public Link(Object o)
{
this.data = o;
this.next = null;
}
public String toString()
{
return data.toString();
}
}
class LinkList {
private Link head;
public LinkList()
{
head = null;
}
the method i created
public Object max(){
Link current=head;
Comparable max=(Comparable)(head.data);
while(current!=null){
if(max.compareTo(current.data)==-1){
max=(Comparable)current.data;
}
current=current.next;
}
return max;
}
the problem is it keep posting this error exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to Comparable
i know u will be getting max in case of numbers usually so u can cast it into int however I'm trying to get the method to work using Comparable any ideas??
Upvotes: 1
Views: 61
Reputation: 59
you can change your Link class property data type to other Class which implemetns Comparable interface. like my code, and override compareTo method:
class Link {
public MyBean data;
public Link next;
public Link(MyBean o) {
this.data = o;
this.next = null;
}
public String toString() {
return data.toString();
}
}
class MyBean implements Comparable<MyBean>{
String name;
// ... other properties
@Override
public int compareTo(MyBean o) {
return System.identityHashCode(this.name) - System.identityHashCode(o);
}
}
Upvotes: 1