Java Generics: type inference in two ways

Suppose I have an easy way to handle two lists:

public static <B> void foo(List<B> list1, List<B> list2) { } 

And I want to call it like this:

 foo(ImmutableList.of(), ImmutableList.of(1)); 

This does not compile because javac not smart enough to realize that I was trying to create two lists of integers. Instead, I should write:

 foo(ImmutableList.<Integer>of(), ImmutableList.of(1)); 

How do I change the declaration of foo so that the first version works as well as the second?

+7
source share
3 answers

I am sure that Java type inference is not efficient enough for unification.

What you can do is return some kind of intermediate object and change the call site in something like:

 foo(list1).and(list2) 

But then it will still be able to output from left to right, so you have to call it like:

 foo(ImmutableList.of(1)).and(ImmutableList.of()); 
+3
source

The only setting in which I foresee that this is an inconvenience for you is when you do this a lot. In this case, you can do

 private static final ImmutableList<Integer> EMPTYINTLIST = ImmutableList.<Integer>of(); 

and use your EMPTYINTLIST in your calls.

+2
source

You can do this by simply changing the general parameter information, and both versions will work. ie

  public static <B> void foo(List<? super B> list1, List<B> list2) { } 

Now both versions will work.

 foo(ImmutableList.of(), ImmutableList.of(1)); foo(ImmutableList.<Integer>of(), ImmutableList.of(1)); 
+1
source

All Articles