Skip to content

Instantly share code, notes, and snippets.

@sushanthmangalore
Created June 11, 2016 18:49
Show Gist options
  • Save sushanthmangalore/0533b55b8c6d0afd2f957752f75dcbd8 to your computer and use it in GitHub Desktop.
Save sushanthmangalore/0533b55b8c6d0afd2f957752f75dcbd8 to your computer and use it in GitHub Desktop.
A brief example of PECS in Java generics - Producer extends, Consumer super
//numberList is a producer of subtypes of numbers. Hence is generified with ? extends Number. Producer->Extends
final List<? extends Number> numberList = DoubleStream.of(-99, 1, 2, 3, 4, 5, 6)
.boxed().collect(Collectors.toList());
//numberList.add(new Integer(1)); //Cannot add integer to this list, even though integer is a subtype of number.
numberList.add(null);//Cannot add anything to numberList other than null
final Number number = numberList.get(0);//Can only get values as Number type
System.out.println(number.doubleValue());
//integerList is a consumer of supertypes of integers. Hence is generified with ? super Integer. Consumer->Super
final List<Object> doubleList = IntStream.of(99, 1, 2, 3, 4, 5, 6).boxed()
.collect(Collectors.toList());
final List<? super Integer> integerList = doubleList; //List<Object> can be assigned
//integerList.add(new Object()); //Cannot add Object to the list, even though Object is a super type of Integer
integerList.add(1);//Integers can be added
//final Integer integer = integerList.get(0); //Cannot get values as Integer or Number
final Object integer = integerList.get(0); //Can only get value in an Object reference
System.out.println(integer.toString());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment