Home arrow static arrow Java Programming [Archive] - List, collections
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - List, collections
This topic has 5 replies on 1 page.

Posts:65
Registered: 4/9/04
List, collections  
Jul 30, 2004 10:49 AM



 
Hi!!!!!!!!!!!

I'm trying to use java.util.List just to be able to sort it. I'm gonna add a class named "JMemoria" in each position of the list.
The problem is that if u want to use the sort method (from de Collections class) u have to implement Comparable interface in "JMemoria" and overwrite the "compareTo()" method. The issue is that compareTo() receives a java.lang.Object as parameter, but in my case it'll receive a "JMemoria" as parameter. How can i fix that??

P.S.: sorry for my english!!!!!

Bye
 

Posts:2,399
Registered: 10/26/00
Re: List, collections  
Jul 30, 2004 10:52 AM (reply 1 of 5)



 
You must cast the Object to a JMemoria.
example:
public int compareTo(Object other) {  return getName().compareTo( ((JMemoria) other).getName());}


Where getName() returns a String.
 

Posts:24,036
Registered: 2/3/03
Re: List, collections  
Jul 30, 2004 10:57 AM (reply 2 of 5)



 
An example compareTo() method may look like this:
public boolean compareTo(Object o) {    if (this == o) return true;    if (!(o instanceof YourClass)) return false;    YourClass yc = (YourClass) o;     // compare 'this' to 'yc' for conditions that may be false.    // e.g., if (this.idNumber != yc.idNumber) return false;    // e.g., if (!this.name.equals(yc.getName()) return false;     return true; }
 

Posts:24,036
Registered: 2/3/03
Re: List, collections  
Jul 30, 2004 10:59 AM (reply 3 of 5)



 
Oh, my. My head's not on straight. Disregard my previous post - I had equals() on the brain.
 

Posts:24,036
Registered: 2/3/03
Re: List, collections  
Jul 30, 2004 10:59 AM (reply 4 of 5)



 
Somebody slap me 30 times with a dead mackerel. LOL
 

Posts:65
Registered: 4/9/04
Re: List, collections  
Jul 30, 2004 11:07 AM (reply 5 of 5)



 
Thank all of u!!!!!!!!!!!!

This compareTo() is similar than overloading < , >, <=, >=, == in C++. Isn't it???

Bye
 
This topic has 5 replies on 1 page.