Is it possible to write a single method that accep

2019-05-06 16:39发布

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());
   }   
}

1条回答
该账号已被封号
2楼-- · 2019-05-06 17:17

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());
}
查看更多
登录 后发表回答