Java Generics (Wildcards)

2018-12-31 16:51发布

I have a couple of questions about generic wildcards in Java:

  1. What is the difference between List<? extends T> and List<? super T>?

  2. What is a bounded wildcard and what is an unbounded wildcard?

7条回答
像晚风撩人
2楼-- · 2018-12-31 17:22

Generic wildcards are created to make methods that operate on Collection more reusable.

For example, if a method has a parameter List<A>, we can only give List<A> to this method. It is a waste for this method's funtion under some circumstances:

  1. If this method only reads objects from List<A>, then we should be allowed to give List<A-sub> to this method. (Because A-sub IS a A)
  2. If this method only inserts objects to List<A>, then we should be allowed to give List<A-super> to this method. (Because A IS a A-super)
查看更多
登录 后发表回答