pecs

Java, generics and PECS: still having trouble understanding the C part; concrete example?

为君一笑 提交于 2019-12-11 16:19:30
问题 I'll post a single link here: Collections.sort(). There have been many posts on SO with regards to the PECS paradigm, including this one. In my own personal code, I use generics quite a lot, but have only ever had the use of the P part (that is, <X extends SomethingElse> ). Collections.sort expects as its generics argument a <T extends Comparable<? super T>> . I fail to see where the super kicks in in there. Do you have a concrete example of why this is necessary? While I am at it, I am

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

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

不想你离开。 提交于 2019-12-05 17:48:20
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()); } } Louis Wasserman You're using Room as a consumer, since it's

What is PECS (Producer Extends Consumer Super)?

旧城冷巷雨未停 提交于 2019-11-25 23:55:32
问题 I came across PECS (short for Producer extends and Consumer super ) while reading up on generics. Can someone explain to me how to use PECS to resolve confusion between extends and super ? 回答1: tl;dr: "PECS" is from the collection's point of view. If you are only pulling items from a generic collection, it is a producer and you should use extends ; if you are only stuffing items in, it is a consumer and you should use super . If you do both with the same collection, you shouldn't use either