简体   繁体   English

Java泛型:通过两个参数推断类型

[英]Java Generics: Inferring types over two parameters

Suppose I have a simple method like this for processing two lists: 假设我有一个简单的方法来处理两个列表:

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

And suppose I want to call it like this: 假设我想这样称呼它:

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

This won't compile, because javac isn't smart enough to figure out I was trying to create two lists of Integers. 这不会编译,因为javac不够聪明,无法弄清楚我正在尝试创建两个Integers列表。 Instead, I have to write: 相反,我必须写:

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

How should I change the declaration of foo to allow the first version to work as well as the second one? 我应该如何更改foo的声明以允许第一个版本和第二个版本一起工作?

I'm pretty sure Java's type inference isn't powerful enough to handle unification. 我很确定Java的类型推断功能不足以处理统一。

What you could do is return an intermediate object of some sort, and change the call site to be something like: 您可以做的是返回某种中间对象,并将调用站点更改为:

foo(list1).and(list2)

But then it would still only be able to infer from left to right, so you'd have to call it as: 但随后它仍然只能从左到右进行推断,因此您必须将其称为:

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

The only setting in which I forsee this being an inconvenience for you is when you do this a lot. 我认为这对您造成的不便是您经常这样做。 In that case you can make a 在这种情况下,您可以

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

and use your EMPTYINTLIST in your calls. 并在通话中使用您的EMPTYINTLIST

You can do that by simply changing the paramter's generic 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM