Java ArrayList contains different objects

Is it possible to create an ArrayList<Object type car,Object type bus> list = new ArrayList<Object type car,Object type bus>() ;

I mean add objects from different classes to one arraylist?

Thanks.

+6
source share
5 answers

Yes, it is 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 .

+15
source

Yes, you can. But you need a generic class for your types of objects. In your case, it will be Vehicle .

So for example:

Car class:

 public abstract class Vehicle { protected String name; } 

Tire 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); } } 
+6
source

Use polymorphism . Let's say you have the parent class Vehicle for Bus and Car .

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

You can add objects of types Bus , Car or Vehicle this list, as the IS-A bus, IS-A car and IS-A car.

Extract an object from the list and work by 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(); } 
+5
source

Unfortunately, you cannot specify more than one type parameter, so you have to find a common superclass for your types and use it. As a last resort, just use Object :

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

Be careful that you will need to give the result to the specific type that you need if you extract the element (to get full functionality, not just normal):

 Car c = (Car)list.get(0); 
+2
source

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

0
source

All Articles