我是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());

}
}


尽管我的boxInt是Integer类型,但列表BoxList仍接受“ apple”。
 我希望它在编译时会出错。
  对此工作的任何帮助将不胜感激。

谢谢,
 迪维亚

最佳答案

当你声明

Box boxInt = *whatever*


Box被视为Box<Object>。因此,boxInt.add("apple")被接受。

您应该这样声明Box

Box<Integer> boxInt=new Box<Integer>(); //Or = new Box<>(); since Java 7


您可能对阅读the oracle documentation about raw types感兴趣。


  使用原始类型时,您实际上会获得泛型行为-盒子为您提供对象

07-26 00:57