Is there a data structure in java can hold different type of objects? For example, if you need use Stack, the element in stack should be in the same type. What if I want a container has different objects inside it?
2 Answers
This sounds like a perfect opportunity for inheritance. Most broadly you could have a List of objects and any type of object can go in. More specifically if you need a list of vehicles you would possibly have the following:
interface Vehicle{
}
class Car implements Vehicle{
}
class Truck implements Vehicle{
}
List<Vehicle> list = new ArrayList<Vehicle>();
list.add(new Car());
list.add(new Truck());
7 Comments
instanceof. :)Airplane that will be invented 2 chapters down the road to fly() we're going to have some funny situations then :PWhatever data structure you are defining can just hold items Object since EVERY class implicitly inherits from Object. However this take a load on your memory be sure to find a way to handle Garbage collection.
E.g. List<Object> or HashMap<Object,Object> obj; or something of that sort.
Maybe if you know all the kinds of Objects that will be held in that data structure you can use the method getClass() within a switch statement to find out what class the Object belongs to. Hope this is of help to you. Please implement this solution only if there is no inheritance between the Objects you plan to use otherwise use @microsby0 's answer
1 Comment
Object take up alot of memory. It is useful to assign them to null when you are done with them so that they become eligible for Gcollection
Objectif you want it to hold anything, or use a parent class for all the objects you want to store. Then you can useinstanceofto process each individual element as intended.instanceofwould lead me to believe the design is potentially wonky.