Skip to content

Instantly share code, notes, and snippets.

@nkonev
Created October 26, 2021 15:13
Show Gist options
  • Save nkonev/5ba703f3429381141ee602d5168d03fe to your computer and use it in GitHub Desktop.
Save nkonev/5ba703f3429381141ee602d5168d03fe to your computer and use it in GitHub Desktop.
PECS.java
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
// https://habr.com/ru/post/559268/
class Class0 { }
class Class1 extends Class0 { }
class Class2 extends Class1 { }
class Class3 extends Class2 { }
class Class4 extends Class3 { }
class Class5 extends Class4 { }
class Class6 extends Class5 { }
class Class7 extends Class6 { }
public class PECS {
public static void someMethodPe(List<? extends Class2> producerList) {
Class2 class2 = producerList.get(0); // correct producing
// wrong consuming - not compiles at all
// producerList.add(new Class2());
}
public static void someMethodCs(List<? super Class3> consumerList) {
consumerList.add(new Class4()); // correct consuming
// not very wrong producing
Object object = consumerList.get(0);
}
public static void main(String[] args) {
ArrayList<Class3> class4s = new ArrayList<>();
class4s.add(new Class4());
class4s.add(new Class5());
someMethodPe(class4s);
System.out.println("Finished PE");
ArrayList<Class2> forConsuming = new ArrayList<>();
forConsuming.add(new Class5());
someMethodCs(forConsuming);
System.out.println("Finished CS");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment