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

前端 未结 2 1282
温柔的废话
温柔的废话 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: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, but that is unnecessarily restrictive. You could instead do this:

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

    Now you can pass in a List instead.

提交回复
热议问题