gpt4 book ai didi

java - 字节类在 Java 的泛型中不起作用

转载 作者:行者123 更新时间:2023-11-30 05:52:36 28 4
gpt4 key购买 nike

我的代码是:-

class abc<T> {
    T a, b;
    abc(T p, T q) {
        a = p;
        b = q;
    }
    void disp() {
        System.out.println("\na = " + a);
        System.out.println("b = " + b);
        System.out.println("a/b is of class type : " + a.getClass().getName());
    }
}

class temp {
    public static void main(String...args) {
        abc<Integer> a1;
        a1 = new abc <Integer>(11, 22);
        abc<Byte> a2 = new abc <Byte>(50,5);
        a1.disp();
        a2.disp();
    }
}

输出:-

temp.java:23: cannot find symbol
symbol : constructor abc(int,int)
location: class abc<java.lang.Byte>
abc <Byte> a2 = new abc <Byte> (50,5);
^
1 error

请帮我解决这个问题。我是 Java 的新手,所以学习泛型。

在这段代码中,我使用了 Integer、Float、Double、String 都工作正常,但是当我进入 Byte 类时,编译器会抛出错误。

最佳答案

这个怎么样?

abc <Byte> a2 = new abc <Byte> ((byte)50, (byte)5);

您作为数字文字提供的参数是整数类型,这些参数会自动装箱到 java.lang.Integer,这就是为什么最初找不到相应方法的原因,除非您明确说明您的文字是字节类型。

关于java - 字节类在 Java 的泛型中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11511097/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com