關於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