猿问

list去除重复项,求教大神,谢谢

遇到的的问题

我建立了一个list,泛型是Bean,Bean中的三个对象都是String类型,如何去除重复项得到这样的结果:


数电, 75, 5

线代, 33, 3

2 相关代码


ArrayList<Bean> list = new ArrayList<Bean>();

            list.add(new Bean("数电", "75", "5"));

            list.add(new Bean("线代", "33", "3"));

            list.add(new Bean("数电", "36", "5"));

            list.add(new Bean("线代", "43", "3"));

3 已经尝试过哪些方法仍然没解决


ArrayList<Bean> listCopy = new ArrayList<Bean>();

for(Bean b:list){

            if (!listCopy.contains(b)) {

                listCopy.add(b);

            }

        }


心有法竹
浏览 353回答 4
4回答

有只小跳蛙

if (!listCopy.contains(b)) {是有问题的。new Bean("数电", "75", "5")和new Bean("数电", "36", "5")是不同的对象,所以contains返回false。遍历listCopy,看看是否存在某个元素,它的第一个字段equals当前对象b的相应字段。for(Bean b:list){&nbsp; &nbsp; if ( ! isDuplicate(listCopy, b) ) {&nbsp; &nbsp; &nbsp; &nbsp; listCopy.add(b);&nbsp; &nbsp; }}boolean isDuplicate (ArrayList<Bean> list, Bean b) {&nbsp; &nbsp; for (Bean elem : list) {&nbsp; &nbsp; &nbsp; &nbsp; if (elem.getCourse().equals(b.getCourse()) return true;&nbsp; &nbsp; }&nbsp; &nbsp; return false;}还有一种方法:重写Bean的equals函数。重写equals看起来很优雅,但是有个前提,即符合equals的语义。第一个字段相等就意味着两个Bean相等吗?这是值得商榷的。equals方法具有很特殊的含义,需慎用。从可读性的角度看,也是直接比较字段比较好。读者一眼就能看出你的意图。

动漫人物

重写equal hash

波斯汪

这是我的代码,运行通过:重写equals(),getSubName是Bean的一个方法@Override&nbsp; &nbsp; public boolean equals(Object obj) {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated method stub&nbsp; &nbsp; &nbsp; &nbsp; if(this == obj){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (obj == null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if(getClass() != obj.getClass()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; final Bean bean = (Bean)obj;&nbsp; &nbsp; &nbsp; &nbsp; if (this.getSubName() != bean.getSubName()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }ArrayList<Bean> listCopy = new ArrayList<Bean>();for(Bean bean:list){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!listCopy.contains(bean)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; listCopy.add(bean);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }

狐的传说

直接Hashset,楼上的太复杂了!!!!
随时随地看视频慕课网APP

相关分类

Java
我要回答