Java Generics (Wildcards)

后端 未结 6 1558
轻奢々
轻奢々 2020-11-22 10:17

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

  1. What is the difference between List and List

6条回答
  •  我寻月下人不归
    2020-11-22 11:00

    There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.

    Collection 
    

    means that it can accept all object who have IS- A relationship with MyObject (i.e. any object which is a type of myObject or we can say any object of any subclass of MyObject) or a object of MyObject class.

    For example:

    class MyObject {}
    
    class YourObject extends MyObject{}
    
    class OurObject extends MyObject{}
    

    Then,

    Collection myObject; 
    

    will accept only MyObject or children of MyObject(i.e. any object of type OurObject or YourObject or MyObject, but not any object of superclass of MyObject).

提交回复
热议问题