java ArrayList包含不同的对象

是否可以创建ArrayList list = new ArrayList() ;

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

谢谢。

是的,这是可能的:

 public interface IVehicle { /* declare all common methods here */ } public class Car implements IVehicle { /* ... */ } public class Bus implements IVehicle { /* ... */ } List vehicles = new ArrayList(); 

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

是的你可以。 但是你需要一个对象类型的公共类。 在你的情况下,这将是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 list = new ArrayList(); list.add(car); list.add(bus); } } 

利用多态性 。 假设你有一辆父母类VehicleCar

 ArrayList list = new ArrayList(); 

您可以将BusCarVehicle类型的对象添加到此列表中,因为总线IS-A车辆,车辆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(); } 

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

 List list = new ArrayList(); 

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

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

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