JAVA ArrayList cant find element via indexOf() [duplicate]

限于喜欢 提交于 2019-12-14 04:14:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!