Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics vs. Method Overloading

Tags:

java

generics

I have 3 methods:

//1 -- check one item
public static <T> void containsAtLeast(String message,
                                       T expectedItem,
                                       Collection<? extends T> found) {
    if (!found.contains(expectedItem))
        Assert.fail("...");        
}

//2 -- check several items
public static <T> void containsAtLeast(String message,
                                       Collection<? extends T> expectedItems,
                                       Collection<T> found) {
    for (T exptetedItem : expectedItems)
        containsAtLeast(message, exptetedItem, found);        
}

//3 -- check several items, without message parameter
public static <T> void containsAtLeast(Collection<? extends T> expectedItems,
                                       Collection<? extends T> found) {
    containsAtLeast(null, expectedItems, found);
}

I would expect that the method //3 invoke //2 but it does not, it invoke method //1. Is there a mistake in what I expect?

*I use sdk 1.7.0_25 and Eclipse 4.3*

like image 745
Ralph Avatar asked Aug 07 '13 12:08

Ralph


1 Answers

Your second method expects the generic type of expectedItems (? extends T) to be a subtype of the generic type of found (T).

In your third method, there is no subtype relationship between the two generic types. They both extend T but could be siblings for example.

So the second method can't be called.

Example: imagine you call the third method with those types:

containsAtLeast(Collection<Integer> e, Collection<String> f)

So the T in your third method is Object. And your first method is called with T = Object too.

like image 126
assylias Avatar answered Oct 20 '22 06:10

assylias