Is it possible to create
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.
ArrayList is a kind of List and List implements Collection interface. The Collection container expects only Objects data types and all the operations done in Collections, like iterations, can be performed only on Objects and not Primitive data types.
Arraylist is a class which implements List interface . It is one of the widely used because of the functionality and flexibility it offers. It is designed to hold heterogeneous collections of objects.
You can add any Java object to a List . If the List is not typed, using Java Generics, then you can even mix objects of different types (classes) in the same List . Mixing objects of different types in the same List is not often done in practice, however.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With