问题
Im writing a short program and I have a problem.
There is a problem with more details.
I have function
public CardStck from(Card card)
int pos = this.cardList.indexOf(card);
card for this example is Card(value=5, color="D")- as u see on the debugging screen Even there is that card im searching for 5(D) (diamond 5 card) in this.cardList the value of pos is -1 (not found)
Could anyone tell me where the problem is?
回答1:
In your card class, implement the "equals" method, like this:
@Override
public boolean equals(Object t){
if(!(t instanceof Card)){
return false;
}
Card c = (Card)t;
//Compare however you want, ie
return (c.getValue() == this.getValue()) & (c.getColor().equals(this.getColor());
}
there may be some other null checks or safety stuff you want to include, like making sure color isn't null etc, but that's the general idea.
来源:https://stackoverflow.com/questions/42445429/java-arraylist-cant-find-element-via-indexof