Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ArrayList contains different objects

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.

like image 420
Serv0 Avatar asked Nov 26 '12 14:11

Serv0


People also ask

Can ArrayList contain different object types?

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.

Can ArrayList have heterogeneous objects?

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.

Can a Java list contains different types?

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.


1 Answers

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();
}
like image 117
Juvanis Avatar answered Sep 23 '22 12:09

Juvanis