java list 存入整数,java - 从List <Integer>中正确删除整数

本文通过示例代码分析了Java中集合与ArrayList在删除元素时的不同行为。当从集合中移除3时,它根据Integer对象进行操作,而ArrayList则按索引删除,导致不同结果。此外,删除null值时,两者都遵循相同逻辑。了解这些差异对于精确地进行元素删除至关重要。
摘要由CSDN通过智能技术生成

这就是诀窍。

我们在这里举两个例子:

public class ArrayListExample {

public static void main(String[] args) {

Collection collection = new ArrayList<>();

List arrayList = new ArrayList<>();

collection.add(1);

collection.add(2);

collection.add(3);

collection.add(null);

collection.add(4);

collection.add(null);

System.out.println("Collection" + collection);

arrayList.add(1);

arrayList.add(2);

arrayList.add(3);

arrayList.add(null);

arrayList.add(4);

arrayList.add(null);

System.out.println("ArrayList" + arrayList);

collection.remove(3);

arrayList.remove(3);

System.out.println("");

System.out.println("After Removal of '3' :");

System.out.println("Collection" + collection);

System.out.println("ArrayList" + arrayList);

collection.remove(null);

arrayList.remove(null);

System.out.println("");

System.out.println("After Removal of 'null': ");

System.out.println("Collection" + collection);

System.out.println("ArrayList" + arrayList);

}

}

现在让我们来看看输出:

Collection[1, 2, 3, null, 4, null]

ArrayList[1, 2, 3, null, 4, null]

After Removal of '3' :

Collection[1, 2, null, 4, null]

ArrayList[1, 2, 3, 4, null]

After Removal of 'null':

Collection[1, 2, 4, null]

ArrayList[1, 2, 3, 4]

现在让我们分析一下输出:

当从集合中删除3时,它调用集合的Integer方法,该方法将object作为参数。 因此它删除了对象3。但是在arrayList对象中,它被索引3覆盖,因此删除了第4个元素。

通过与Object删除相同的逻辑,在第二个输出中的两种情况下都会删除null。

因此,要删除号码Integer这是一个对象,我们将明确需要传递3作为object。

这可以通过使用包装器类Integer进行转换或包装来完成。

例如:

Integer removeIndex = Integer.valueOf("3");

collection.remove(removeIndex);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值