Java – Remove element from linked list JAVA

java

OK here is my problem. I have a linked list of card objects.

I have the following method

  public void removeCard(Card card){
        cards.remove(card);

  }

if I create Card c = new Card(5,C); for example

and there is a card with the exact same values 2, and C in the linked list (cards).

If I call the method CardPile.remove(card)
I dont get any errors, but the element that's equal to the parameter card is not removed.
Any ideas why this is not happening?

import java.util.LinkedList;

public class CardPile {

    final char [] suit = {'C','D','H','S'};
    final char [] rank = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'};

    LinkedList<Card> cards;


    public CardPile(){
            cards = new LinkedList<Card>();
    }


    public void addCard(Card card){
            cards.addLast(card);
    }
    public void removeCard(Card card){
            cards.remove(card);

    }
    public void removeSpecial(Card card){
            LinkedList<Card> temp = new LinkedList<Card>();
            for(int i=0; i<cards.size(); i++){
                    if(cards.get(i).equals(card)){
                            temp.add(cards.get(i));

                    }
            }
            cards = temp;
    }

    public void listCards(){
            for(int i=0; i<cards.size(); i++){
                    System.out.print(cards.get(i).toString()+" ");
            }
            System.out.println();
    }

    public boolean isEmpty(){
            if(cards.size()==0)
                    return true;
            else
                    return false;
    }

    public Card drawCard(){
            return cards.removeLast();
    }

    public boolean hasCard(Card card){
            int index = 0;
            boolean contained = false;
            if(cards.size()==0){
                    System.out.println("error, cards size is 0");
                    return false;
            }
            else{
                    while(index<cards.size() && !contained){
                            if(cards.get(index).isEqual(card)){
                                    System.out.println("Card found");
                                    contained=true;
                            }
                            index++;
                    }
            }

            return contained;
    }
}

Best Solution

I bet the Card class doesn't override equals() and hashcode() method.

The default implementation by Object class simply checks "==", i.e. if two variables point to the same object instance. You need to override equals() and hashcode() to provide proper equal-ness check. See excellent discussion on the topic here - http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

With proper equals() and hashcode(), your code can be further simplied. For example, the hasCard() method can simply call List method contains().