文章目录
List与Set判断重复对象的区别
① List只依赖于equals方法
② Set依赖于hashCode、equals方法
TreeSet和HashSet
1、TreeSet 是二叉树实现的,Treeset中的数据是自动排好序的,不允许放入null值。
2、HashSet 是哈希表实现的,HashSet中的数据是无序的,可以放入null,但只能放入一个null,两者中的值都不能重复,就如数据库中唯一约束。
3、HashSet要求放入的对象必须实现HashCode()方法,放入的对象,是以hashcode码作为标识的,而具有相同内容的 String对象,hashcode是一样,所以放入的内容不能重复。
关于hashmap存储一个对象,中间改变对象的值,为什么再remove不能用新名字来删除
你重写了对象的hashcode方法,并且内部用到了属性来计算hashcode
那么当你修改了属性后,它的hashcode自然变了,那么它就在原来的hashmap里找不到了,自然删除不掉。
TreeSet删除修改了属性的对象
思路:创建新set集合,筛选出删除的对象
其他各种方法都没用
Set<AiPropayGather> set1=aiPropayRecordGather.getPropaySet();
Set<AiPropayGather> set2=new TreeSet<AiPropayGather>();
AiPropayGather remo=new AiPropayGather();
for(AiPropayGather ai : set1) {
if(! ai.getId().equals(aiPropayGather2.getId())){
set2.add(ai);
}
}
aiPropayRecordGather.setPropaySet(set2);
Java List的remove()方法陷阱
List调用remove(index)方法后,会移除index位置上的元素,index之后的元素就全部依次左移
- for循环遍历List删除元素时,让索引同步调整
for(int i=0;i<list.size();i++){
if(list.get(i)==3)
**list.remove(i--);**
}
System.out.println(list);
- 倒序遍历List删除元素–正确!
for(int i=list.size()-1;i>=0;i--){
if(list.get(i)==3){
list.remove(i);
}
}
System.out.println(list);
- 迭代删除List元素–正确!
Iterator<Integer> it=list.iterator();
while(it.hasNext()){
if(it.next()==3){
--it.remove();--
}
}
System.out.println(list);
注意: 迭代器这样删除是错误的
Iterator<Integer> it=list.iterator();
while(it.hasNext()){
Integer value=it.next();
if(value==3){
--list.remove(value)--
}
}
System.out.println(list);