1

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?

3
  • You can use Object if you want it to hold anything, or use a parent class for all the objects you want to store. Then you can use instanceof to process each individual element as intended. Commented Sep 23, 2014 at 13:32
  • What about using List<Object>? Or generally speaking: What about using generics? Commented Sep 23, 2014 at 13:32
  • Any of them. Whether or not you should do this kind of depends; using instanceof would lead me to believe the design is potentially wonky. Commented Sep 23, 2014 at 13:32

2 Answers 2

7

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()); 
Sign up to request clarification or add additional context in comments.

7 Comments

This sounds like a perfect example for re-heating my understanding on inheritance, thanks
Its a super useful concept and very important in java. Glad to help!
Good answer microsby0. For posterity's sake, you could also mention how we get the Car and the Truck back out using instanceof. :)
What do you mean "get the Car and Truck back out"?
@TheLostMind well, when he wants the Airplane that will be invented 2 chapters down the road to fly() we're going to have some funny situations then :P
|
0

Whatever 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

what I actually meant was items of type 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.