本文介绍了JAVA ArrayList无法通过indexOf()找到元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个简短的程序,但我遇到了问题.

Im writing a short program and I have a problem.

有更多细节问题.

我有功能

public CardStck from(Card card)
int pos = this.cardList.indexOf(card);

如您在调试屏幕上看到的,本例中的

card是Card(value = 5,color ="D")-甚至在此card.im卡中我正在搜索5(D)(菱形5卡). pos的值为-1(未找到)

card for this example is Card(value=5, color="D")- as u see on the debugging screenEven 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?

推荐答案

在卡片类中,实现等于"方法,如下所示:

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());
}

您可能还需要包含其他一些null检查或安全性内容,例如确保颜色不为null等,但这是通常的想法.

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.

这篇关于JAVA ArrayList无法通过indexOf()找到元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:34