1

Given:

public static <T> void copy(List<? super T> dest, List<? extends T> src)

I have seen this page: Confusion over Java generic method type inference

But I am still confused, dasblinkenlight says that as long as the Object you pass in is consistent then the code should compile.

Does this mean that the first argument type will help determine what is valid for the second?

public class Hello {

    public static void main(String[] args){
        ArrayList<Animal> dogs = new ArrayList<>();
        ArrayList<Marly> marlies = new ArrayList<>();

        copy(dogs,marlies);
    } 

    public static <T> void copy(List<? super T> dest, List<? extends T> src{

    }  
}

class Animal{}
class Dog extends Animal { }
class Beagle extends Dog { }
class Marly extends Beagle{ }

pretty much every which way I have changed around these two lists it compiles, as long as the first is higher in the inheritance hierarchy.

Can someone help explain a little further

OLIVER.KOO
  • 4,857
  • 2
  • 21
  • 47
SallyRothroat
  • 585
  • 1
  • 5
  • 17
  • does this post clarify a bit? https://stackoverflow.com/questions/1368166/what-is-a-difference-between-super-e-and-extends-e – csunday95 Aug 10 '17 at 20:29
  • Got it. So I guess it is correct to say that in situations like this there really is no T and what really matters is what happens in the method body and how to the Types relate to each other. – SallyRothroat Aug 10 '17 at 20:40

1 Answers1

0

The method signature uses two different wildcards:

  • <? super T>
  • <? extends T>

Differences explained here: Difference between <? super T> and <? extends T> in Java

Every time you call this method, the java compiler will try to find a T such that both arguments satisfy their condition. It seems when having multiple choices, the compiler will pick the most specific T it can.

So

// fails because there is no superclass of Dog that is a subclass of Animal
copy(new ArrayList<Dog>(), new ArrayList<Animal>())
// chooses T = Marly because it is most specific solution
copy(new ArrayList<Animal>(), new ArrayList<Marly>())
tkruse
  • 8,363
  • 5
  • 43
  • 70