问题
I want to write a for loop using the for-each syntax:
for(Obj o : ArrayList<Obj>)
As in this example:
class Car{
int number;
public Car(int num){ number = num; }
int getNumber(){ return this.number; }
}
class CarPark{
ArrayList<Car> cars;
public CarPark(){ cars = new ArrayList<Car>(); }
}
public class Main{
public static void main(String[] args){
CarPark p = new CarPark();
p.add(new Car(123));
p.add(new Car(456));
p.add(new Car(789));
for(Car c : p.cars){
System.out.println(c.getNumber());
}
}
}
How do I write the loop? Is this syntax possible?
回答1:
Your for-each loop has no problem.
There is just one point you must modify. To adding new Car
objects to ArrayList
, use p.cars.add()
.
public static void main(String[] args) {
CarPark p = new CarPark();
p.cars.add(new Car(123));
p.cars.add(new Car(456));
p.cars.add(new Car(789));
for (Car c : p.cars) {
System.out.println(c.getNumber());
}
}
So the ArrayList
cars
is a member of CarPark
class object p
, that you can access it through p.cars
.
回答2:
Yes. You can do that. Apart from the naming convention, everything seems to be fine.
Now you are iterating using foreach loop.
if (p.getCars() != null) {
for (Car car : p.getCars()) {
System.out.println(car.getCarNumber());
}
}
If you are looking for a traditional for loop:
for (int i = 0; i < p.size(); i++) {
System.out.println(p.get(i).getNumber());
}
The foreach loop is usually preferable to the traditional style.
回答3:
With Java 8 you can use a simple lambda expression:
p.cars.forEach(c -> System.out.println(c.getNumber()));
This is equivalent to your for
-loop.
来源:https://stackoverflow.com/questions/32550645/writing-a-for-each-loop-to-get-objects-from-an-arraylist