关于list的remove方法感悟


list的remove方法主要重载了两种,包括remove(index)和remove(object)两种。今天在项目中,主要使用到了clone方法深度复制了list。其实两个list中的对象的属性值完全一样。但是在另外的源listS中无法remove该对象,原因是两个list中的对象对应的内存地址是不一样的。

 

示例:

 



public class Person implements Cloneable{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Object clone() {   
Person o = null;   
        try {   
            o = (Person) super.clone();   
        } catch (CloneNotSupportedException e) {   
            e.printStackTrace();   
        }   
        return o;   
    }
}

 

 

 

public class Test {
public static void main(String args[]){
List<Person> list=new ArrayList<Person>();
Person p1 =new Person();
p1.setName("1");
p1.setAge(1);
list.add(p1);
List<Person> list1=new ArrayList<Person>();
for(int j=0;j<list.size();j++){
Person p=(Person) list.get(j).clone();
list1.add(p);
}
System.out.println(list.size());
for(int k=0;k<list.size();k++){
Person s=list.get(k);
for(int y=0;y<list1.size();y++){
Person t=list1.get(y);
if(t.getName().equals(s.getName())){
for(int h=0;h<list.size();h++){
if(s.getName().equals(list.get(h).getName())){
list.remove(h);
}
}
System.out.println(list.size());
}
}
}
System.out.println(list.size());
}

}

 

此时输出结果为: 1 0 0

如果

 for(int h=0;h<list.size();h++){
 if(s.getName().equals(list.get(h).getName())){
 list.remove(h);
 }

 }

如果该段代码换为list.remove(t)是不好使的。

运行结果为:  1  1   1

 

正确答案:  1  0  0


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM