我有以下方法:
public final NavigableSet<AnimalCard> getCowTradeCardsSorted() {
TreeMap<AnimalCard,AnimalCard> ssa = new TreeMap<AnimalCard,AnimalCard>();
Iterator<E> i = this.cowTradeCards.iterator();
System.out.println("Input is:"+this.cowTradeCards.toString());
while (i.hasNext()) {
E a = i.next();
System.out.println("Adding 2 ssa:"+a.toString());
ssa.put((AnimalCard) a ,(AnimalCard) a); //this.getCountOfOneCard(a));
System.out.println("ssa is now"+ssa.toString());
}
System.out.println("returnvalue is"+ ssa.descendingKeySet().toString());
return ssa.descendingKeySet().descendingSet();
}
我希望以下输出作为返回值:[1000,500,160,10]
但我得到 [1000]
这是控制台的输出:
Input is:[1000, 10, 160, 500]
Adding 2 ssa:1000
ssa is now{1000=1000}
Adding 2 ssa:10
ssa is now{1000=10}
Adding 2 ssa:160
ssa is now{1000=160}
Adding 2 ssa:500
ssa is now{1000=500}
returnvalue is[1000]
怎么了?看起来树图将所有值绑定到第一个键?
ps:this.cowtradecards 是一个数组列表,但这并不重要
public class AnimalCard extends Card { ..........
// super has this :public int getValue() {
// return this.value;
// }
@Override
public int compareTo(Object o) {
// Pufferelement vom Typ AnimalCard
AnimalCard buffer;
// Kontrolle, ob übergebenes Objekt vom Typ "AnimalCard" ist
if (o instanceof MoneyCard) { <--------------- here is the error !!!!! should be AnimalCard !
// wenn ja, dann Typcasting vornehmen
buffer = (AnimalCard) o;
if (super.getValue() < buffer.getValue()) {
return -1;
}
if (super.getValue() > buffer.getValue()) {
return 1;
}
return 0;
} else {
// not an "AnimalCard"
}
return 0;
}
after i fixed the compareto:
Input is:[1000, 10, 160, 500]
Adding 2 ssa:1000
ssa is now{1000=1000}
Adding 2 ssa:10
ssa is now{10=10, 1000=1000}
Adding 2 ssa:160
ssa is now{10=10, 160=160, 1000=1000}
Adding 2 ssa:500
ssa is now{10=10, 160=160, 500=500, 1000=1000}
returnvalue is[1000, 500, 160, 10]