O'Reilly logo

Just Java™ 2 by Peter van der Linden

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Wildcarding a Generic Parameter

Say we want to write a method that will shuffle the elements in a Collection. We can shuffle a list regardless of what type the elements are. We don't want to have to write one shuffle method that works on List<Integer> and another for List<String> and another for List<Byte>. We need to give shuffle() a parameter that is a “List of anything” and have it move elements around. The usual way to express “List of anything” is “List of Object”, which in the new world of generics is written “List <Object>”

However, there's a big problem with passing around a nice, type-safe, homogeneous “List <String>” and letting someone untrustworthy, like our shuffle() method, get their hands on it as a “List <Object>” A parameter ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required