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.
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);
}
}
Vehicle class called createVehicle, which will try to parse the input string, and create an appropriate object. For instance, the function could look-up which is the manufacturer of the vehicle - if it is BMW, then this is a Car, in other case it is a Bus.Car. And then while constructing an object, you would call new Car(s[0],s[1],s[2],s[3],s[4]), where s[2] is obviously the car brand.Comparator.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);