java ArrayList包含不同的对象

时间:2012-11-26 14:34:23

标签: java object arraylist

是否可以创建 ArrayList<Object type car,Object type bus> list = new ArrayList<Object type car,Object type bus>();

我的意思是将不同类的对象添加到一个arraylist中?

感谢。

5 个答案:

答案 0 :(得分:17)

是的,有可能:

public interface IVehicle { /* declare all common methods here */ }
public class Car implements IVehicle { /* ... */ }
public class Bus implements IVehicle { /* ... */ }

List<IVehicle> vehicles = new ArrayList<IVehicle>();

vehicles列表将接受任何实现IVehicle的对象。

答案 1 :(得分:7)

是的,你可以。但是你需要一个对象类型的公共类。在您的情况下,这将是Vehicle

例如:

车辆类:

public abstract class Vehicle {
    protected String name;
}

公交车课程:

public class Bus extends Vehicle {
    public Bus(String name) {
        this.name=name;
    }
}

汽车类:

public class Car extends Vehicle {
    public Car(String name) {
        this.name=name;
    }
}

主要课程:

public class Main {
    public static void main(String[] args) {
        Car car = new Car("BMW");
        Bus bus = new Bus("MAN");
        ArrayList<Vehicle> list = new ArrayList<Vehicle>();
        list.add(car);
        list.add(bus);
   }
}

答案 2 :(得分:5)

使用多态。假设您有VehicleBus的父类Car

ArrayList<Vehicle> list = new ArrayList<Vehicle>();

您可以将类型BusCarVehicle的对象添加到此列表中,因为总线 IS-A Vehicle,Car IS-A 车辆和车辆 IS-A 车辆。

从列表中检索对象并根据其类型进行操作:

Object obj = list.get(3);

if(obj instanceof Bus)
{
   Bus bus = (Bus) obj;
   bus.busMethod();
}
else if(obj instanceof Car)
{
   Car car = (Car) obj;
   car.carMethod();
}
else
{
   Vehicle vehicle = (Vehicle) obj;
   vehicle.vehicleMethod();
}

答案 3 :(得分:2)

不幸的是,您不能指定多个类型参数,因此您必须为您的类型找到一个公共超类并使用它。一个极端的例子就是使用Object

List<Object> list = new ArrayList<Object>();

请注意,如果检索项目,您需要将结果转换为所需的特定类型(以获得完整功能,而不仅仅是常用功能):

Car c = (Car)list.get(0); 

答案 4 :(得分:0)

创建一个类并使用多态。然后在点击中选取对象,使用instanceof。

相关问题