众所周知,java 缓存范围为 -128 到 127 的整数。现在,我有一个类容器,如下所示:
public class Container<T>{
private List<T> elements;
public boolean add(T t){
//add the element to the container
//if elements already contains t such that
//there is e from elements so e == t
//the IllegalArgumentException should be thrown
}
}
现在,当我尝试创建 Container<Integer> container
时然后像这样添加一些内容
container.add(1);
container.add(2);
container.add(1); //here the IllegalArgumentException is being thrown.
我遇到了异常。 这不是我想要的行为。我需要为添加到容器中的任何整数创建不同的对象。我怎样才能做到这一点?
最佳答案
使用 new
运算符显式创建 Integer
的新实例。
container.add(new Integer(1));
container.add(new Integer(2));
container.add(new Integer(1));
关于java - 如何区分同一个整数对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31446598/