如何判断ArrayList中是否存在某一个自定义对象

在Java开发中,使用ArrayList时可能需要判断列表中是否存在特定的自定义对象。ArrayList的contains(Object o)方法依赖于对象的equals()方法。未重写equals()时,比较的是对象引用;重写后,可根据业务需求定制比较逻辑。以Student类为例,当需要根据id判断对象是否相同时,需重写equals(),并考虑null的情况。测试证明,正确重写后可以按预期判断对象是否存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发中经常用到ArrayList,有时候需要判断ArrayList中,是否已经存在某一个自定义的实体对象,该如何判断呢?

ArrayList的Api文档中有这样一个方法:boolean contains(Object o),用来判断是否存在某一个Object。

我们先来看一下这个方法实现的具体源代码:

    /**
     * Returns <tt>true</tt> if this list contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this list contains
     * at least one element <tt>e</tt> such that
     * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
     *
     * @param o element whose presence in this list is to be tested
     * @return <tt>true</tt> if this list contains the specified element
     */
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain th
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值