2015-05-20 170 views
2

我写了我自己的类叫做Person,变量为String name,int agedouble height以及toString()。然后我创建了Person s的ArrayList,并添加了几个实例。它打印良好。现在我想写一个方法,当我写一个名字时,检查ArrayList那个名字的实例,如果是的话,就删除那个实例。我应该怎么做?从ArrayList中删除对象

这里是我写的东西:

import java.util.*; 
public class PersonManager { 

    public static void main(String[] args) { 
     ArrayList<Person> people = new ArrayList<>(); 
     Scanner keyboard = new Scanner(System.in); 

     people.add(new Person("Adam ", 29, 177.5)); 
     people.add(new Person("Bernadette", 19, 155.2)); 
     people.add(new Person("Carl", 45, 199)); 

     for (Person p : people) 
      System.out.println(p); 

     System.out.println("Select person to remove"); 
     String name = keyboard.nextLine(); 


     // if there is a person with that name in the list, that 
     //person gets removed from the list 

    } 

} 
+4

你认为你应该怎么做? –

+0

看起来你已经知道如何遍历一个'ArrayList.'你怎么知道比较两个'String'对象? – CubeJockey

+0

看一下'ArrayList'的方法,看看'add'的反面是什么,并试试看。如果它不起作用,请展示你的尝试,我们可以提供帮助。 –

回答

0

要导航到Person与给定的名称,然后从列表中删除。
所以,你可以使用迭代经历名单,同时:

Iterator personIter = people.iterator(); 
while(personIter.hasNext()){ 
    Person p = (Person)personIter.next();  
    if(name != null && name.equals(p.getName())){ 
     personIter.remove(); 
     break; //will prevent unnecessary iterations after match has been found 
    } 
} 
1

如果您使用的是Java 8,不介意从原来的创建一个新的列表,你可以用JAVA 8个流这样的:

ArrayList<Person> people = new ArrayList<>(); 

    people.add(new Person("Adam ", 29, 177.5)); 
    people.add(new Person("Bernadette", 19, 155.2)); 
    people.add(new Person("Carl", 45, 199)); 
    String nameToRemove = "name"; 
    people = people.stream().filter((t) -> !t.getName().equals(nameToRemove)).collect(Collectors.toList()); 
1

正如@MasterMind所说:如果您有权访问JDK 8功能,则可以使用筛选(如其示例中所示),或者使用新的Collection#removeIf(..)方法。在你的情况,这将是这样的:

people.removeIf(person -> person.getName().equals(name)); 

对工作的完整示例见here