Java:使用ArrayList进行迭代

时间:2013-06-09 13:01:55

标签: java arraylist foreach iteration

鉴于这些课程:

public class Car {

private int registrationNumber;
private String automaker;
private String colour;
private int numberOfSeats;

public Car {
setRegistrationNumber(int regNum);
setAutomaker(String automakerName);
setColour(String carColour);
setNumberOfSeats(int seats);
}

public int getRegistrationNumber() {
return registrationNumber;
}

public void setRegistrationNumber(int regNum) {
registrationNumber = regNum;
}

public String getAutomaker() {
return automaker;
}

public void setAutomaker(String automakerName) {
automaker = automakerName;
}

public String getColour() {
return colour;
}

public void setColour(String carColour) {
colour = carColour;
}

public int getNumberOfSeats() {
return numberOfSeats;
}

public void setNumberOfSeats(int seats) {
numberOfSeats = seats;
}
}

public class Bicycle {

private String colour;
private int height; // The height of the bike measured in centimeters

public Bicycle {
setColour(String bicycleColour);
setHeight(int bicycleHeight);
}

public String getColour() {
return colour;
}

public void setColour(String bicycleColour) {
colour = bicycleColour;
}

public int getHeight() {
return height;
}

public void setHeight(int bicycleHeight) {
height = bicycleHeight;
}
}

import java.util.ArrayList;
public class CarCollection {

private ArrayList<Car> cars;

public CarCollection {
cars = new ArrayList<Car>();
}

public int getNumberOfSeatsInCollection() {
for(Car numberOfSeats : cars) {
return numberOfSeats;
}
}
}

现在我需要一些帮助来完成这项任务:创建一个类VehicleCollection。车辆可以是汽车或自行车,但是将来可以添加其他类型的车辆。 VehicleCollection必须具有返回集合中总座位数的方法。自行车总是有一个座位。

有人可以告诉我他们将如何解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

public abstract class Vehicle {
    public abstract int getNumberOfSeats();
}

让您的所有车辆都延伸到车辆。然后实现getNumberOfSeats方法

现在

List<Vehicle> vehicleList=new ArrayList<>();

public int getNumberOfSeatsInCollection() {
int totalSeats=0'
for(vehicle v: vehicleList) {
totalSeats=totalSeats+v.getNumberOfSeats();
}
return totalSeats;
}

答案 1 :(得分:0)

最好的方法是在此类中创建Vehicle创建可验证的SeatsNumberInterface(如接口),以及实现此接口示例BikeSeats和CarSeats的两个类。 SeatsNumberInterface必须具有方法数量的席位和继承此接口的类(BikeSeats和CarSeats)具有此方法实现。创建新Car时,您可以设置其CarSeatInterface接口。这是战略设计模式。

车辆类

public class Vehicle{
    private interface SeatsNumberInterface seats;

...

public void setSeatsNumberInterface(SeatsNumberInterface seats){
    thi.seats = seats;
}

public getSeatNumber(){
    seats.getSeatsNumber();
}
} 

座位接口

public interface SeatsNumberInterface{
    public int getSeatsNumber();
}

BikeSeats类

public class BikeSeats implements SeatsNumberInterface{
    public int getSeatsNumber(){
        return 1;
}
}

自行车课

public Bike extends Vehicle{
...
}

如何创建课程

Vehicle vehicle = new Bike();
vehicle.setSeatsNumberInterface(new BikeSeats);
System.out.println("Seats number: " + vehicle.getSeatNumber);