4

As a followup to this question, is it possible to write a single method that adds a Dog to a suitable room? (In this example, it would accept either an Animal room or a Dog room.) Or am I forced to write two distinct methods as below? (I can't even rely on overloading because of type erasure).

public class Rooms {
   interface Animal {}
   class Dog implements Animal {}
   class Room<T> {
      void add(T t) {}
   }

   void addDogToAnimalRoom(Room<Animal> room) {
      room.add(new Dog());
   }

   void addDogToDogRoom(Room<Dog> room) {
      room.add(new Dog());
   }   
}
Community
  • 1
  • 1
Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246

1 Answers1

5

You're using Room as a consumer, since it's accepting the new Dog, so Josh Bloch's famous PECS acronym applies.

void addDogToDogRoom(Room<? super Dog> room) {
  room.add(new Dog());
}
Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • 1
    Oh *that's* what super is for :) – Jeff Axelrod Mar 29 '12 at 16:22
  • 3
    Yep! You're using `List` as a consumer, since it's accepting the new Dog, so Josh Bloch's famous PECS acronym applies. – Louis Wasserman Mar 29 '12 at 16:23
  • This is the danger of learn-as-you-go programming. I "read" his book, but only the parts that were relevant at the time. I think understanding this could have saved me much unnecessary refactoring. Please feel free to suggest (or just edit) a better question title. – Jeff Axelrod Mar 29 '12 at 16:28