-1

Im writing a short program and I have a problem.

State before fail

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?

5
  • 2
    Have you implemented equals()? Commented Feb 24, 2017 at 18:06
  • You need to override your hashCode and equals method to check your equality so that indexof method would select accordingly Commented Feb 24, 2017 at 18:06
  • Did you override equals/hasCode method in the Card class? Commented Feb 24, 2017 at 18:07
  • Have you overwritten Equals() in your Card class? Commented Feb 24, 2017 at 18:07
  • 1
    Anyone hear an echo? Commented Feb 24, 2017 at 18:09

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

5 Comments

It works, thank you so much!
equals() shouldn't throw an exception when the object is of another type.
I was providing the general solution. If he wants to do type checking etc. he can. No need to down vote. I stated explicitly that it wasn't a complete example.
I don't mind that it's incomplete, I mind that it's wrong. Type checking isn't optional; you must check t instanceof Card before trying to cast (after which you don't need the null check btw).
@shmosel satisfactory? if not, feel free to make an edit.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.