java - 如何遍历 ArrayList of Objects 的对象 ArrayList?

标签 java object arraylist iteration

举个例子:

假设我有一个类调用 Gun。 我有另一个类调用 Bullet

Gun 有一个 Bullet 的 ArrayList。

要遍历 Gun 的 Arraylist ..而不是这样做:

ArrayList<Gun> gunList = new ArrayList<Gun>();
for (int x=0; x<gunList.size(); x++)
    System.out.println(gunList.get(x));

我们可以像这样简单地遍历Gun的ArrayList:

for (Gun g: gunList) System.out.println(g); 

现在,我想迭代并打印出我的第三个 Gun 对象的所有 Bullet:

for (int x=0; x<gunList.get(2).getBullet().size(); x++)  //getBullet is just an accessor method to return the arrayList of Bullet 
    System.out.println(gunList.get(2).getBullet().get(x));

现在我的问题是:我如何使用 ArrayList 迭代打印出枪支对象列表,而不是使用传统的 for 循环?

最佳答案

您想遵循与以前相同的模式:

for (Type curInstance: CollectionOf<Type>) {
  // use currInstance
}

在这种情况下,它将是:

for (Bullet bullet : gunList.get(2).getBullet()) {
   System.out.println(bullet);
}

关于java - 如何遍历 ArrayList of Objects 的对象 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24943663/

相关文章:

java - 您推荐哪种适用于 Apache Maven 的软件安装程序插件?

javascript - 对年份数组进行排序(包括 BCE)

java - 无法从 Java 中的 ArrayList 访问对象的方法

java - 如何从 ArrayList 打印某个变量

java - 下载htmlunit时出现异常

java - 显示图表故障的下一个和上一个按钮

java - 从 ArrayList<String> 矩阵创建制表符分隔的 .txt 表

Java:将不同类型的对象放入 ModelCollection 的 ArrayList 中。接口(interface)?

java - 如何从 src 文件夹调用测试类并使用 maven 构建

php - 如何修复 PHP 中的 'Creating default object from empty value' 警告