【问题标题】:Removing object from ArrayList从 ArrayList 中删除对象
【发布时间】:2015-08-02 06:37:30
【问题描述】:

我用变量String nameint agedouble height 以及toString() 编写了自己的类Person。然后我创建了Persons 的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

    }

}

【问题讨论】:

  • 你觉得应该怎么做?
  • 看起来你已经知道如何循环遍历一个 ArrayList. 了关于比较两个 String 对象你知道什么?
  • 看看ArrayList的方法,看看add的反面可能是什么,试一试。如果它不起作用,请展示您的尝试,我们可以提供帮助。

标签: java methods arraylist instance


【解决方案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());

【讨论】:

    【解决方案2】:

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

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

    请参阅here 了解完整的示例。

    【讨论】:

      【解决方案3】:

      您想使用给定名称导航到 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
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-03-11
        • 1970-01-01
        • 2015-08-05
        • 2013-04-17
        • 1970-01-01
        • 1970-01-01
        • 2014-05-04
        相关资源
        最近更新 更多