java ArrayList contains different objects

前端 未结 5 1280
攒了一身酷
攒了一身酷 2020-12-09 06:28

Is it possible to create ArrayList list = new ArrayList();

I mean add obje

相关标签:
5条回答
  • 2020-12-09 06:46

    Create a class and use polymorphism. And then to pick up the object in the click, use instanceof.

    0 讨论(0)
  • 2020-12-09 06:48

    Get use of polymorphism. Let's say you have a parent class Vehicle for Bus and Car.

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

    You can add objects of types Bus, Car or Vehicle to this list since Bus IS-A Vehicle, Car IS-A Vehicle and Vehicle IS-A Vehicle.

    Retrieving an object from the list and operating based on its type:

    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();
    }
    
    0 讨论(0)
  • 2020-12-09 06:51

    You can't specify more than one type parameter unfortunately, so you'll have to find a common superclass for your types and use that. An extreme case would be just using Object:

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

    Be careful that you will need to cast the result to the specific type that you need if you retrieve an item (to get full functionality, not just the common one):

    Car c = (Car)list.get(0); 
    
    0 讨论(0)
  • Yes, it's possible:

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

    The vehicles list will accept any object that implements IVehicle.

    0 讨论(0)
  • 2020-12-09 07:05

    Yes you can. But you need a common class to your object types. In your case this would be Vehicle.

    So for instance:

    Vehicle class:

    public abstract class Vehicle {
        protected String name;
    }
    

    Bus class:

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

    Car class:

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

    Main class:

    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);
       }
    }
    
    0 讨论(0)
提交回复
热议问题