Is it possible to create
ArrayList
;
I mean add obje
Create a class and use polymorphism. And then to pick up the object in the click, use instanceof.
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();
}
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);
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
.
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);
}
}