【发布时间】:2012-11-14 01:20:21
【问题描述】:
是否可以创建
ArrayList<Object type car,Object type bus> list = new ArrayList<Object type car,Object type bus>();
我的意思是将不同类的对象添加到一个数组列表中?
谢谢。
【问题讨论】:
是否可以创建
ArrayList<Object type car,Object type bus> list = new ArrayList<Object type car,Object type bus>();
我的意思是将不同类的对象添加到一个数组列表中?
谢谢。
【问题讨论】:
是的,有可能:
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 的对象。
【讨论】:
是的,你可以。但是您需要一个对象类型的通用类。在您的情况下,这将是 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);
}
}
【讨论】:
Vehicle 类中有一个名为createVehicle 的函数,它将尝试解析输入字符串,并创建一个适当的对象。例如,该函数可以查找车辆的制造商——如果是BMW,那么这是Car,否则是Bus。
Car 类的表示。然后在构造对象时,调用new Car(s[0],s[1],s[2],s[3],s[4]),其中s[2] 显然是汽车品牌。
Comparator。
使用多态性。假设您有一个父类 Vehicle 用于 Bus 和 Car。
ArrayList<Vehicle> list = new ArrayList<Vehicle>();
您可以将 Bus、Car 或 Vehicle 类型的对象添加到此列表,因为 Bus IS-A Vehicle、Car IS-A Vehicle 和车辆 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<Object> list = new ArrayList<Object>();
请注意,如果您检索项目,您需要将结果转换为您需要的特定类型(以获得完整功能,而不仅仅是普通功能):
Car c = (Car)list.get(0);
【讨论】:
创建一个类并使用多态性。然后在点击中拾取对象,使用instanceof。
【讨论】: