The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


The sameCard Method

The word "same" is one of those things that occur in natural language that seem perfectly clear until you give it some thought, and then you realize there is more to it than you expected.

For example, if I say "Chris and I have the same car," I mean that his car and mine are the same make and model, but they are two different cars. If I say "Chris and I have the same mother," I mean that his mother and mine are one and the same. So the idea of "sameness" is different depending on the context.

When you talk about objects, there is a similar ambiguity. For example, if two Cards are the same, does that mean they contain the same data (rank and suit), or they are actually the same Card object?

To see if two references refer to the same object, we can use the == operator. For example:

    Card card1 = new Card (1, 11);
    Card card2 = card1;

    if (card1 == card2) {
      System.out.println ("card1 and card2 are the same object.");
    }

This type of equality is called shallow equality because it only compares the references, not the contents of the objects.

To compare the contents of the objects---deep equality---it is common to write a method with a name like sameCard.

  public static boolean sameCard (Card c1, Card c2) {
    return (c1.suit == c2.suit && c1.rank == c2.rank);
  }

Now if we create two different objects that contain the same data, we can use sameCard to see if they represent the same card:

    Card card1 = new Card (1, 11);
    Card card2 = new Card (1, 11);

    if (sameCard (card1, card2)) {
      System.out.println ("card1 and card2 are the same card.");
    }

In this case, card1 and card2 are two different objects that contain the same data

so the condition is true. What does the state diagram look like when card1 == card2 is true?

In Section 7.11 I said that you should never use the == operator on Strings because it does not do what you expect. Instead of comparing the contents of the String (deep equality), it checks whether the two Strings are the same object (shallow equality).



Last Update: 2011-01-24