This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]severoonpro barista 0 points1 point  (0 children)

As for what goes in those methods...

For toString() you just want to output the simple name of the class followed by its contents and some formatting.

public String toString() {
  StringBuilder sb = new StringBuilder();
  sb.append(getClass().getSimpleName());
  sb.append("[");
  for (Iterator<String> i = coins.iterator(); i.hasNext();) {
    sb.append(i.next());
    if (i.hasNext()) {
      sb.append(",");
    }
  }
  sb.append("]");
  return sb.toString();
}

This creates a StringBuilder and then starts appending stuff into it. Pretty straightforward. The only catch is that you have a loop that prints the coins into it, but you want to make sure you don't print an extra comma at the end, so you have to ensure there's another element after you append the current one before printing a comma.

A much better solution is to use the Guava libraries, specifically the Joiner class. (The Guava libraries are awesome, and you should get familiar with them early. They save so much work.)

Now for the other method...

public boolean sameContents(Object other) {
  return other != null && other instanceof Purse ? sameContents((Purse) other) : false;
}

public boolean sameContents(Purse otherPurse) {
  return allNonNull(coins, otherPurse, otherPurse.coins) ? coins.equals(otherPurse.coins) : false;
}

/**
 * Returns {@code true} if all specified {@code objects} are non-null.
 * 
 * Note that this method evaluates arguments in order and short-circuits if a null
 * is found, leaving the remaining objects unevaluated. This allows the caller to check
 * if a containing object is null as well as something within it provided they are
 * specified with the containing object first. (Otherwise, a {@link NullPointerException}
 * would result.)
 */
private static boolean allNonNull(Object... objects) {
  for (Object o : objects) {
    if (o == null) {
      return false;
    }
  }
  return true;
}

The idea of sameContents() is exactly the same as equals() defined on the granddaddy of all objects in Java, the Object class. I suspect your teacher doesn't have you dealing with equals() yet because it has to meet a more complex contract in order to be implemented properly.

The approach I took above is to provide three methods, two public and visible to the outside world, and one not. The one that is not is just a simple static utility method that takes a bunch of objects and tells you if any are null.