Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 泛型类型参数是如何工作的?_Java_Generics - Fatal编程技术网

Java 泛型类型参数是如何工作的?

Java 泛型类型参数是如何工作的?,java,generics,Java,Generics,我是java中泛型的新手。 我尝试了以下方法: Entity class: public class Box<T> { private List<T> boxList; public List<T> getBoxList() { if (this.boxList == null) this.boxList = new ArrayList<T>(); return this.

我是java中泛型的新手。 我尝试了以下方法:

Entity class:
public class Box<T> {
    private List<T> boxList;

    public List<T> getBoxList() {
        if (this.boxList == null)
            this.boxList = new ArrayList<T>();

        return this.boxList;
    }

    public void setBoxList(List<T> boxList) {
        this.boxList = boxList;
    }

}

Test class:

public class Client {
public static void main(String[] args) {
    Box box = new Box();
    box.getBoxList().add(1);
    box.getBoxList().add("one");
System.out.println(box.getBoxList());

Box boxInt=new Box<Integer>();
boxInt.getBoxList().add("apple");
System.out.println(boxInt.getBoxList());

}
}
实体类:
公共类箱{
私有列表框列表;
公共列表getBoxList(){
if(this.boxList==null)
this.boxList=new ArrayList();
返回此.boxList;
}
公用箱列表(列表箱列表){
this.boxList=boxList;
}
}
测试等级:
公共类客户端{
公共静态void main(字符串[]args){
Box=新的Box();
box.getBoxList().add(1);
getBoxList().add(“一”);
System.out.println(box.getBoxList());
Box-boxInt=新的Box();
getBoxList().add(“苹果”);
System.out.println(boxInt.getBoxList());
}
}
虽然我的boxInt是整数类型,但list-BoxList仍然接受“apple”。 我期望它在编译时抛出一个错误。 任何关于这项工作的帮助都将不胜感激

谢谢, Divya

当您申报时

Box boxInt = *whatever*
被视为
。因此,
boxInt.add(“苹果”)
被接受

您应该这样声明

Box<Integer> boxInt=new Box<Integer>(); //Or = new Box<>(); since Java 7
Box-boxInt=new-Box()//或=新框();自Java7以来
你可能对阅读感兴趣

当使用原始类型时,您基本上得到了预泛型行为—一个框为您提供了对象

当你申报时

Box boxInt = *whatever*
被视为
。因此,
boxInt.add(“苹果”)
被接受

您应该这样声明

Box<Integer> boxInt=new Box<Integer>(); //Or = new Box<>(); since Java 7
Box-boxInt=new-Box()//或=新框();自Java7以来
你可能对阅读感兴趣

当使用原始类型时,您基本上得到了预泛型行为—一个框为您提供了对象


以后可以通过注意编译器警告来避免这种情况,因为它们会告诉您使用的是“原始类型”(在本例中为非类型框)。不幸的是,一些IDE在默认情况下不启用这些警告;例如,在Netbeans中,您必须在编辑器提示中启用“标准javac警告”。您可以通过关注编译器警告来避免将来出现这种情况,因为它们会告诉您错误地使用了“原始类型”(在本例中为非类型框)。不幸的是,一些IDE在默认情况下不启用这些警告;例如,在Netbeans中,必须在编辑器提示中启用“标准javac警告”。