generics, method signatures, assignments

后端 未结 2 1207
感情败类
感情败类 2020-12-12 00:01

I thought I understood this but obviously not...

I have a method signature like so:

void doSomething(List typeAs){...}

2条回答
  •  温柔的废话
    2020-12-12 00:47

    A generic class TypeA is a different type from TypeA. You can't pass in a parameter of type TypeA where the method expects a TypeA. Also TypeA is a different type from TypeA, so the same constraints apply.

    The classic example (from Effective Java, 2nd Ed. AFAIR) is: we have containers for animals (Container) and as subclasses of Animal we have Lion and Butterfly. Now, if you have a method

    void func(Animal animal);
    

    it will accept both lions and butterflies. However, this function

    void func(Container animalContainer);
    

    will not accept a Container, neither a Container. Do realize that a strong cage useful for keeping lions safely would not stop butterflies from flying away, and vice versa a thick but light net to hold butterflies would not stand a chance against a lion.

    If you really are sure that any kind of animal container suits you, declare your function like this:

    void func(Container animalContainer);
    

    Back to your case, I guess the only method to accept both List and List> would be something like this:

    void doSomething(List list);
    

提交回复
热议问题