首页 > 编程 > Java > 正文

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

2019-11-11 01:42:29
字体:
来源:转载
供稿:网友

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;    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表