Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Cesar Gonzalez   on Mar 01 In Java Category.

  
Question Answered By: Dennis Hayes   on Mar 01

I've been sitting here watching the posts and I have decided that I need
to speak up:

All of the examples have been incorrectly demonstrating what the
compareTo() method  is supposed return: -1, 0 or 1 depending on whether
the value passed in is less than, equal to, or greater than the object
which has the compareTo() method. The compareTo() should not return  the
int value of the object  being passed in - that is not its purpose.

The original posters problem is that the Object t which is passed to the
method should be cast  to his object type. Since the original poster did
not say what his object type  is, I am just going to call it MyObject:

public class MyObject{

public int  getNumber(){
return number;
}

public string  getId(){
return id;
}

public int compareTo(Object o){
int n = ((MyObject)o).getNumber();
if(n < number){
return -1;
} else if(n == number){
return 0;
} else {
return 1;
}
}

private int number;
private String id;

}

You can see that MyObject implements the compareTo() method by casting
the incoming object to a MyObject type if possible and then getting the
number from the incoming object and comparing that to its own number.
This is the correct usage of the compareTo() method.

A ClassCastException is the normal result when you try to compare two
objects which are not of the same type, unless the comparator knows that
it should expect different object types, usually be requiring some sort
of common interface instead.

Share: 

 

This Question has 6 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on How Do I Cast Object To Int ? Or get search suggestion and latest updates.


Tagged: