Main intention or Purpose of Wildcard notation' ? extends T'

前端 未结 2 1283
温柔的废话
温柔的废话 2021-01-12 10:33

I have this bit of ( counter-intuitive ) observations about generic wildcard notation used in collections. The purpose of the wildcard notation List

相关标签:
2条回答
  • 2021-01-12 10:48

    Extends is for reading from a list , and Super is for writing to a list. Read page 7 of this tutorial : http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

    Read these lecture notes from MIT class in software construction: http://stellar.mit.edu/S/course/6/sp11/6.005/courseMaterial/topics/topic2/lectureNotes/Generics-spring11/Generics-spring11.pdf

    hopefully these will make everything clear with wildcards and generics.

    0 讨论(0)
  • 2021-01-12 10:56

    Yes, your observation is correct. However, in the case you show, it's not very useful (you're electing to ignore useful information about the list). The assignment is more useful when it's implicit as you call a library function.

    For example, say you had a library function that closed a collection of InputStreams. You could accept a List<InputStream>, but that is unnecessarily restrictive. You could instead do this:

    public void closeAll(Collection<? extends InputStream> streams) {
        for ( InputStream stream : streams ) {
            stream.close();
        }
    }
    

    Now you can pass in a List<FileInputStream> instead.

    0 讨论(0)
提交回复
热议问题