What is PECS (Producer Extends Consumer Super)?

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? 16 s 16 tl;dr: “PECS” is from the collection’s point of view. If you are only pulling items from a generic collection, it … Read more

Is List a subclass of List? Why are Java generics not implicitly polymorphic?

I’m a bit confused about how Java generics handle inheritance / polymorphism. Assume the following hierarchy – Animal (Parent) Dog – Cat (Children) So suppose I have a method doSomething(List<Animal> animals). By all the rules of inheritance and polymorphism, I would assume that a List<Dog> is a List<Animal> and a List<Cat> is a List<Animal> – … Read more

Difference between

This question already has answers here: What is PECS (Producer Extends Consumer Super)? (16 answers) Closed 3 years ago. What is the difference between List<? super T> and List<? extends T> ? I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List<? super … Read more

How to create a generic array in Java?

Due to the implementation of Java generics, you can’t have code like this: public class GenSet<E> { private E a[]; public GenSet() { a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation } } How can I implement this while maintaining type safety? I saw a solution on the Java forums that goes like this: … Read more

How do I use reflection to call a generic method?

What’s the best way to call a generic method when the type parameter isn’t known at compile time, but instead is obtained dynamically at runtime? Consider the following sample code – inside the Example() method, what’s the most concise way to invoke GenericMethod<T>() using the Type stored in the myType variable? public class Sample { … Read more

Create Generic method constraining T to an Enum

I’m building a function to extend the Enum.Parse concept that Allows a default value to be parsed in case that an Enum value is not found Is case insensitive So I wrote the following: public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum { if (string.IsNullOrEmpty(value)) return defaultValue; foreach (T item in Enum.GetValues(typeof(T))) … Read more