调用泛型方法java的编译器错误

耶拿

我用很少的方法创建了一个通用类。我只想调用该方法并添加值,但是它不起作用。这是代码

public interface GenericInterface<T> {
    public T getValue();
    public  void setValue(T t);
}

public class FirstGeneric<T> implements GenericInterface<T> {
    private T value;

    public FirstGeneric(T _value) {
        this.value = _value;
    }

    @Override
    public T getValue() {
        return value;
    }

    @Override
    public void setValue(T t) {
        this.value = t;
    }

    @SuppressWarnings("unchecked")
    public static <T> T addValues(FirstGeneric<T> myGeneric, FirstGeneric<T> myGeneric1) {
        T result = null;
        if (myGeneric != null && myGeneric1 != null) {
            T t1 = myGeneric.getValue();
            T t2 = myGeneric1.getValue();
            result = (T) t1.toString().concat(t2.toString());
            System.out.println("Result is:=" + result);
        }
        return result;
    }

    public static void main(String args[]) {
        Integer int1 = 1;
        FirstGeneric<Integer> myInt = new FirstGeneric<Integer>(int1);
        String value = "Hello";
        FirstGeneric<String> myString = new FirstGeneric<String>(value);
        addValues(myString,  myInt);
    }
}

但是我在最后一行收到编译错误。

类型为FirstGeneric的方法addValues(FirstGeneric,FirstGeneric)不适用于自变量(FirstGeneric,FirstGeneric)

我做错了什么?谢谢。

他们是

addValues有一个通用类型参数,这意味着您不能同时将aFirstGeneric<Integer>和a传递给它FirstGeneric<String>

为了使addValues(myString, myInt)调用有效,您可以在方法中定义两个通用类型参数:

public static <T,U> String addValues(FirstGeneric<T> myGeneric, FirstGeneric<U> 
   myGeneric1) {
    String result = null;
    if (myGeneric != null && myGeneric1 != null) {
        T t1 = myGeneric.getValue();
        U t2 = myGeneric1.getValue();
        result = t1.toString().concat(t2.toString());
        System.out.println("Result is:=" + result);
    }
    return result;
}

请注意,我将return类型更改为String,因为它显然是String(由产生的t1.toString().concat(t2.toString())),因此您不能将其强制转换为T并希望T将其转换为String

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Java泛型-编译器错误

泛型和迭代器的Java编译器错误

Java:递归泛型编译器错误

使用Java泛型并将List作为方法参数的编译器错误并引发泛型异常

解决泛型类型约束中的编译器错误

Java泛型:Eclipse中未显示编译器错误

Eclipse Java 编译器推断出错误的泛型类型?

责任链设计原理中的Java泛型编译器错误

Java泛型错误:来自命令行编译器的不可转换类型

为什么运算符<对于Java泛型有编译器错误?

编译器如何推断泛型方法的类型?

在Java中转换为泛型方法类型变量时出现编译器警告

泛型混淆:欺骗编译器

当运行时类型也是泛型类型时,将方法引用用作期望使用泛型类型接口的方法的lambda时,编译器错误

为什么通过实例调用静态方法不是Java编译器的错误?

尝试在闭包中使用泛型时发生意外的编译器错误

条件类型添加了额外的泛型编译器错误

将@SuppressWarnings(“ unchecked”)泛型添加到单行会产生eclipse编译器错误

使用 Linq exceptBy 函数的泛型类中出现奇怪的编译器错误

泛型类型扩展无效的重新声明编译器错误

Scala编译器在使用泛型的方法中说“ T没有可用的TypeTag”

为什么编译器不允许从 peek 方法返回的泛型不是可选的?

为什么Java编译器失去构造函数实例化轨道泛型类型的?

如何提取从Java泛型类类满足编译器?

当我用Java迭代非泛型映射时,编译器会抱怨

为什么这个java接口定义使用编译器接受的泛型?

此代码是否利用Java编译器泛型验证限制

Java-本地类和泛型,为什么会出现编译器警告?

保存ArrayLists时由泛型引起的Java编译器警告