gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:40:11 25 4
gpt4 key购买 nike

举个例子:

假设我有一个类调用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com