collection的remove方法对HashSet ArrayList的不同
来源:互联网 发布:深入理解java 虚拟机 编辑:程序博客网 时间:2024/05/24 04:36
ArrayList底层是一个数组,每次加入就是依次向后加入,当删除的时候,比较的是传入的参数是否equals保存在ArrayList中的某个元素,与Hashcode无关,所以一个类如果仅仅重写了equals方法而没有重写hashcode方法,这要两个对象equals返回true,那么就可以成功删除。
HashSet底层是HashMap,根据前面的介绍必须使用hashcode和equals来查找到待删除的元素,所以仅仅重写equals而没有重写hashcode是删除不了的。
Address类首先仅仅重写了equals方法,而没有重写hashcode方法
public class Address{private String detail;public Address(String detail){this.detail = detail;}public String getDetail(){return detail;}public void setDetail(String detail){this.detail = detail;}//@Override//public int hashCode()//{//final int prime = 31;//int result = 1;//result = prime * result + ((detail == null) ? 0 : detail.hashCode());//return result;//}@Overridepublic boolean equals(Object obj){if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Address other = (Address) obj;if (detail == null){if (other.detail != null)return false;}else if (!detail.equals(other.detail))return false;return true;}}
下面在ArrayList 和HashSet中测试以两个equals的对象,一个加入,然后使用另外一个删除
public static void main(String[] args) throws Throwable{Address a1 = new Address("shanghai");Address a2 = new Address("shanghai");ArrayList<Address> list = new ArrayList<Address>();list.add(a1);list.remove(a2);//加入a1,然后根据a2删除,能成功删除, list为空System.out.println(list.isEmpty());HashSet<Address> set = new HashSet<Address>();set.add(a1);set.remove(a2);//同样的操作在HashSet中就不管用,删除不了,set不为空System.out.println(set.isEmpty());}
下面把上面Address类中的重写hashcode方法的注释取消掉,结果是无论ArrayList还是HashCode都能成功删除
在没有重写hashcode的情况下,如果向set中加入两个equals的对象是可以的,例如:
HashSet<Address> set = new HashSet<Address>();set.add(a1);set.add(a2);Object[] as = set.toArray();//set中的两个对象是相等的,这样就出现了代码不健壮的情况System.out.println(as[0].equals(as[1]));
总结:
ArrayList底层是数组,可以加入重复的,使用remove删除时判断的标准是equals方法。
HashSet底层是一个HashMap,不能加入重复的,重复的标准是先比较hashcode,然后比较equals,使用remove删除时同样是这样的比较原则
1 0
- collection的remove方法对HashSet ArrayList的不同
- ArrayList和HashSet中contains方法的不同
- ArrayList的remove()方法
- ArrayList的方法:remove(object o) 、remove(int index)、removeAll(Collection c)时间复杂度的比较
- 容器Collection的总结一 Vector ArrayList LinkedList HashSet TreeSet
- 细说ArrayList的remove方法
- ArrayList、Iterator的remove方法
- ArrayList和HashSet的Contains()方法
- ArrayList,HashSet的比较
- Collection 和 Iteractor 的remove方法
- Collection和List接口的remove方法
- java collection Iterator的remove()方法
- ArrayList的remove方法的一个特性
- 详解ArrayList的remove的方法
- 利用HashSet特性实现对ArrayList的去重
- ArrayList和HashSet对的比较及HasCode分析
- 今天遇到的对List,ArrayList的remove方法的一个小问题
- 关于arraylist 的remove 与contain 方法
- Android开发之数据存储与访问(2)
- linux中安装Qt 4.8.5
- 各种网络协议知识归纳
- c/c++中内存区域划分大总结!!!
- C语言位运算实现循环移位
- collection的remove方法对HashSet ArrayList的不同
- hdu 2492 离散化,树状数组,逆序数
- 一个单词是否为其他字符串的字串
- Hint&ordered&leading&use_nl
- 数据结构-循环和递归
- C++编程学习50个经典网站!
- Linux内核设计的艺术——搭建Linux0.11系统环境
- NSString常用代码
- 之前常见的额问题,不知道怎么分析.