0
votes

Why can I not add an integer to the consumer?

import java.util.*;

public class Test 
{
    public static void main(String[] args)
    {
        List<Integer> integers = new ArrayList<>();
        test(integers);
    }

    public static <T> void test(List<? super T> to)
    {
        to.add(32);
    }
}

According to PECS (Producer extends, Consumer super), I use super, but this error occurs:

Test.java:13: error: no suitable method found for add(int)
        to.add(32);
          ^
    method Collection.add(CAP#1) is not applicable
      (argument mismatch; int cannot be converted to CAP#1)
    method List.add(CAP#1) is not applicable
      (argument mismatch; int cannot be converted to CAP#1)
  where T is a type-variable:
    T extends Object declared in method <T>test(List<? super T>)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Object super: T from capture of ? super T
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
1
Within test, what is known about T?Savior
Your consumer doesn't provide any specific information about its type. How can you guarantee that T will always be numeric type which accept 32 as its representation? If you would have List<? super Integer> to compiler would not have problem with allowing to add 32 to it.Pshemo

1 Answers

2
votes

Simple answer: because there's no T relation to int in your example.

It will work like this however:

public class Test
{
    public static void main(String[] args)
    {
        List<Integer> integers = new ArrayList<>();
        test(integers, 32);
    }

    public static <T> void test(List<? super T> to, T elem)
    {
        to.add(elem);
    }
}

And also like this:

public class Test
{
    public static void main(String[] args)
    {
        List<Integer> integers = new ArrayList<>();
        test(integers);
    }

    public static void test(List<? super Integer> to)
    {
        to.add(32);
    }
}

The reason is you need to "explain" compiler how is your collection type relate to the element type.

PS have a read here