34754

Generics Collections PECS

Question:

I have a question about this method from java.util.Collections:

public class Collections { public static <T> void copy(List<? super T> dest, List<? extends T> src) { for (int i=0; i<src.size();i++) dest.set(i,src.get(i)); } }

I understand how <? super T> works, however, I don't understand why the first parameter is List<? super T> instead of List<T>. I think it's useless in this situation.<br /> Using List<T> should work as well, shouldn't it?<br /> Could you give me some examples to understand it if possible, please?

Thanks.

Answer1:

No, it makes sense. For example, consider this situation:

<ul><li>T is InputStream</li> <li>dest is a List<Object></li> <li>src is a List<FileInputStream></li> </ul>

That works absolutely fine. Of course, you <em>could</em> make T either Object or FileInputStream in this situation - but imagine you were calling this <em>from</em> a method with a signature of:

public void doSomething(List<? super InputStream> streams) { // I want to use copy in here for some reason }

You don't know it's a List<InputStream> - only that it's a List<? super InputStream>. If the dest parameter in copy were <em>just</em> List<T>, we'd be stuck... but with the way it <em>is</em> written, we're fine.

It also makes sense in terms of what we require from the destination list - we <em>just</em> need to be able to set values of T within it. Likewise all we require of the source list is that we can get values of T from it. <? super T> and <? extends T> express those requirements well.

Answer2:

If you break it down in why the List is being used it will be a bit more clear.

When a method intends to populate a list, you could restrict it to use a specific type T, however often you might want to be less restrictive.

For example, lets say you have a method populateWithStudents(List<Student> list) And you have Student extend Person

This means that you can't use that method with a List<Person> to fill it with Student objects, even though Student extends Person.

So if on the other hand we would like to allow that we change it to populateWithStudents(List<? super Student> list). This way we're saying that as long as we can fit a Student in the list, no matter if it is a list of Student objects, or a list of any of its superclasses, it is allowed.

This is not just when populating obviously, but this example helps understand the concept.

Recommend

  • ObjectDisposedException on a ASP.NET Core 2.0 MVC custom database initializer class
  • JPA EntityManager and JavaFx [duplicate]
  • Sequelize belongsToMany additional attributes in join table
  • Mocking OpenXML with Moq
  • CRM Dynamics How to set short list - long list relationship
  • Starting Bootstrap tour with a button after ending tour once
  • How to work with Mailgun API in CodeIgniter; Forbidden error in curl_exe()
  • How do I add a trailing slash for Django MPTT-based categorization app?
  • Why is search query table displaying table Headers, and not data in BeautifulSoup (Python)?
  • Null Space Binary Matrix : Java
  • Parsing string using the Scanner class
  • android 3G signal strength
  • What is the diff. between default.properties and project.properties?
  • Making query to find nearest multiple(Lat,Long) from the single(Lat,Long)
  • Get last 15 lines from a large file in SFTP with phpseclib [duplicate]
  • How to escape xpath in php
  • How to modify the way a ForeignKey field is rendered in a Django admin page to avoid browser crash?
  • Yii Bootstrap not loading JS files
  • C++11: Why rvalue reference parameter implicitly converted to lvalue
  • Showing image on a acro text field position
  • Adding horizontal slider to QTableWidget
  • Shiny - change the size (padding?) of dropdown menu (select tags) smaller
  • Unable to start a WebView from an AsyncTask
  • C# code can't “see” the methods in my C++ dll
  • How to make Rss News Reader application in android …? [closed]
  • Copy and paste data from multiple workbooks to a worksheet in another Workbook
  • All Event listing on specified date in Google Calender api (V3) in java?
  • What is the difference between dynamically creating a script tag and statically embed a script tag?
  • How to run chrome.tabs.insertCSS from the background page on each page?
  • Creating 2d platforms using JavaScript
  • Add font awesome icon to custom add to cart button in Woocommerce 3
  • How to write seo friendly url's using htaccess?
  • gnuplot - How to make zmin equal to zmax keeeping autoscale on z axis
  • Is there a better way for handling SpatialPolygons that cross the antimeridian (date line)?
  • Error handeling in antlr 3.0
  • Change cell value based on cell color in google spreadsheet
  • Apple Mach-O Linker error (“duplicate symbol”)
  • Angular FormGroup won't update it's value immediately after patchValue or setValue
  • Access to a Matlab gui from the web
  • How to check if object is null in Java?