Java属性,List的方法contains()。

本文介绍了一种在Java中合并两个包含Student对象的List集合的方法,并确保去除重复对象。通过覆盖equals方法来判断两个Student对象是否相等,从而实现有效的过滤。

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

List的方法contains().

当有两个: List<Student> listA 和 List<Student> listB,而要把 listA 和listB都放在同一个集合List<Student> listAll 里面,假如listA与listB集合里面有相同的Student对象,所以两个集合相加的时候要进行过滤。

代码如下:list.contains(o),系统会对list中的每个元素e调用o.equals(e),方法,加入list中有n个元素,那么会调用n次o.equals(e),只要有一次o.equals(e)返回了true,那么list.contains(o)返回true,否则返回false。因此为了很好的使用contains()方法,我们需要重新定义下Student类的equals方法,根据我们的业务逻辑,如果两个Student对象的orderId相同,那么我们认为它们代表同一条记录 :

public List<Student> addList(List<Student> listA, List<Student> listB){

    List<Student> list = new ArrayList<>();

    if(listA != null){
        list.addAll(listA);
    }
    if(listB != null){
        Iterator<Student> it = listB.iterator();
        while(it.hasNext()){
            Student student = it.next();
            if(!list.contains(student)){
                list.add(student);
            }
        }
    }
    return list;
}
class Student{
    private int age;
    private int stuo;
    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getStuo() {
        return stuo;
    }

    public void setStuo(int stuo) {
        this.stuo = stuo;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    @Override
    public boolean equals(Object object){
        if(this == object)
            return true;
        if(object == null)
            return false;
        if(this.getClass() != object.getClass())
            return false;
        final Student student = (Student) object;
        if(this.getStuo() != student.getStuo())
            return false;
        if(this.getName() != student.getName())
            return false;
        if(this.getAge() != student.getAge())
            return false;
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值