Java泛型:类型参数T隐藏类型T [英] Java generics: the type parameter T is hiding the type T

查看:1092
本文介绍了Java泛型:类型参数T隐藏类型T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么java编译器在translate方法中给我类型参数T隐藏了类型T?

  public static interface Translator< T,E> {
电话(T t);
}

public static< T,E>列表与LT E - 代替; translate(List< T> 1,Translator< T,E> t){
..
}

如果我删除类型参数T

  public static< E>列表与LT E  - 代替; translate(List  1,Translator< T,E> t)

警告消失,但现在我不能做
$ b $

 列表< Long> l = new ArrayList<>(); 
列表< String> r = translate(l,new Translator< Long,String>(){..})

它给了我这个错误

$ pre $ lt; code>方法translate(List< T>,GFn.Translator< T,E>)$ b $ (List< Long>,new GFn.Translator< Long,String>(){})
$ p>

解决方案

我使用下面的代码,并且不会收到任何警告消息:

  public class Main {

public static interface Translator< T,E> {
电话(T t);
}

public static< T,E>列表与LT E - 代替; translate(List< T> 1,Translator< T,E> t){
List< E> result = new ArrayList< E>(); (T item:l)

result.add(t.call(item));
}
返回结果;
}

public static class TranslatorImpl implements Translator< Long,String> {

@Override
public String call(Long aLong){
return String.valueOf(aLong);



$ b public static void main(String [] args)throws IOException {
List< Long> items = new ArrayList< Long>();
items.add(10L);
items.add(20L);
items.add(30L);
System.out.println(translate(items,new TranslatorImpl()));
}

}


Why java compiler is giving me "the type parameter T is hiding the type T" in the "translate" method ?

public static interface Translator<T, E> {
  E call(T t);
}

public static <T, E> List<E> translate(List<T> l, Translator<T, E> t) {
  ..
}

If i remove the type parameter T

public static <E> List<E> translate(List<T> l, Translator<T, E> t)

the warning disappeared but now i cannot do

List<Long> l = new ArrayList<>();
List<String> r = translate(l, new Translator<Long, String>() { .. })

cause it give me this error

The method translate(List<T>, GFn.Translator<T,E>) 
in the type GList is not applicable for the arguments 
(List<Long>, new GFn.Translator<Long,String>(){})

解决方案

I'm using the following code and don't get any warning messages:

public class Main {

public static interface Translator<T, E> {
    E call(T t);
}

public static <T, E> List<E> translate(List<T> l, Translator<T, E> t) {
    List<E> result = new ArrayList<E>();
    for (T item: l) {
        result.add(t.call(item));
    }
    return result;
}

public static class TranslatorImpl implements Translator<Long, String> {

    @Override
    public String call(Long aLong) {
        return String.valueOf(aLong);
    }
}


public static void main(String[] args) throws IOException {
    List<Long> items = new ArrayList<Long>();
    items.add(10L);
    items.add(20L);
    items.add(30L);
    System.out.println(translate(items, new TranslatorImpl()));
}

}

这篇关于Java泛型:类型参数T隐藏类型T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆