java - 如何区分同一个整数对象?

标签 java list integer

众所周知,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/

相关文章:

java - 如何添加到main中的数组?

java - AbstractList::equals() 的 JDK 实现不会首先检查列表大小是否相等

javascript 循环遍历 li 属性并更改每个项目的值

java - 在 Java 中安全解码 Base64 字符数组

java - 根据日期字段对文件进行分组时出错

python - 经过一段时间后如何更新显示的元素?

python - 如何将数字四舍五入到指定的上限或下限?

java - 用户输入Integer,用这个Int调用数组时总是返回0?

Javascript 没有将我的计数器变量视为数字

java - Eclipse java 中的默认语法颜色