【问题标题】:Print ArrayList Object [duplicate]打印 ArrayList 对象 [重复]
【发布时间】:2016-12-19 20:42:33
【问题描述】:

我已经创建了几个对象,我只想打印 ArrayList 中对象的一个​​参数:

Superhero batman = new Superhero("Bruce", 26, "Batman");
Human rachel = new Human("Rachel", 24);

Superhero ironman = new Superhero("Tony", 35, "Ironman");
Human pepper = new Human("Pepper", 22);

List<Human> people = new ArrayList<Human>();
people.add(batman);
people.add(rachel);
people.add(ironman);
people.add(pepper);

我要打印:

Bruce
Rachel
Tony
Pepper

【问题讨论】:

  • 迭代列表中的人(在每次迭代中访问每个人),为每个人获取其名称并打印它。如果您对此解决方案有任何疑问,请询问有关此解决方案的更具体问题。
  • 请用您的问题展示您解决此问题的尝试。
  • 摆脱 Pshemo 所说的遍历人员列表,并获取对象名称。 for( Human human : people ) { System.out.println( human.getName() ); }
  • 以后,请用你的问题表现出你最好的善意尝试——否则我们不会知道你做错了什么,否则你的问题读起来就像是在乞求代码。跨度>
  • 抱歉下次再来

标签: java arraylist


【解决方案1】:

在 Java 8 之前

for (Human human : people) {
    System.out.println(human.getName());
}

从 Java 8 开始

people.stream().map(Human::getName).forEach(System.out::println);

【讨论】:

    【解决方案2】:
    for(Human human : people) {
        System.out.println(human.getName());
    }
    

    这应该打印人员列表中每个人的姓名。您应该在 Human 类中有方法:

    getName() {
        return this.name;
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2016-11-10
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      相关资源
      最近更新 更多