Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 12. Generics > Using Bounded Wildcards in Methods

Using Bounded Wildcards in Methods

In the section "Using the ? Wildcard" above, you learned that passing different type variables to a generic type creates different Java types, despite a parent-child relationship between the type variables. In many cases, you may want a method to accept a List of different types. For example, if you have a getAverage method that returns the average of numbers in a list, you may want to pass a list of integers or a list of floats or a list of another number type. However, if you write List<Number> as the argument type to getAverage, you won't be able to pass a List<Integer> instance or a List<Double> instance because List<Number> is a different type from List<Integer> or List<Double>. You can use List as a raw type or use a wildcard, but this is depriving you of type safety checking at compile time because you can also pass a list of anything, such as an instance of List<String>. You could use List<Number>, but you must always pass a List<Number> to the method. This would make your method less useful because you work with List<Integer> or List<Long> probably more often than with List<Number>.

There is another rule to circumvent this restriction, i.e. by allowing you to define an upper bound of a type variable. This way, you can pass a type or its subtype. In the case of the getAverage method, you may be able to pass a List<Number> or a List of instances of a Number subclass, such as List<Integer> or List<Float>.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial