Making item sortable (implementing Comparable)
Hello,
The problem is in this part of the code:
Code java:
CardBase[] tmp = new CardBase[13];
System.arraycopy(deck, range*13, tmp, 0, 13);
Collections.sort(Arrays.asList(tmp));
The error I get is:
Code :
cannot find symbol
symbol : method sort(java.util.List<CardBase>)
location: class java.util.Collections
Collections.sort(Arrays.asList(tmp));
CardBase is an interface which looks like this:
Code java:
public interface CardBase {
public int compareTo(Object o);
public Suit setSuit();
public Suit getSuit();
public String getShortSuit();
}
The deck array which is being copied with System.arraycopy method to a tmp array is:
Code java:
CardBase[ ] deck = new Card[52];
I know that to be able to sort items, I need to make it sortable first. Card class is the class which implements CardBase and Comparable interfaces. So from my point of view everything should be ok, but it isn't. Anyone could tell me where the mistake is? If it is not enough information, I can paste full code here.
P.S
compareTo method is ok, but I'll post it anyway:
Code java:
public int compareTo(Object o) {
if(o instanceof Card) {
Card tmp = (Card) o;
int i = this.suit.compareTo(tmp.getSuit());
if(i == 0)
return this.label.compareTo(tmp.getLabel());
else
return i;
}
return -1;
}
Re: Making item sortable (implementing Comparable)
From the point of view of the sorting algorithm, CardBase isn't sortable even though it's actually holding Cards (simply having the CompareTo method declared inside of CardBase doesn't make it Comparable).
Consider this:
If you had a second class implement CardBase (say Card2) that wasn't Comparable, you could still add it to the array tmp. The sorting algorithm would then puke because it can't sort items of type Card2.
The simple fix is rather than having your Card class directly implement the Comparable interface, have the CardBase interface extend Comparable so you guarantee that all classes that implement CardBase will be Comparable.
Re: Making item sortable (implementing Comparable)
Don't have a solution.
The API doc for sort says:
All elements in the list must implement the Comparable interface.
I don't see where you honor this requirement
Re: Making item sortable (implementing Comparable)
Quote:
Originally Posted by
Norm
Don't have a solution.
The API doc for sort says:
All elements in the list must implement the Comparable interface.
I don't see where you honor this requirement
Just read what I wrote once more ;)
TIP:
Quote:
Card class is the class which...
Anyway, with helloworld922 advice I have solved it. Thanks!