Is it possible to write a single method that accepts a generic parameter of varying abstraction?

社会主义新天地 提交于 2019-12-07 08:20:37

问题


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:


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


来源:https://stackoverflow.com/questions/9929370/is-it-possible-to-write-a-single-method-that-accepts-a-generic-parameter-of-vary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!