nubela
nubela

Reputation: 17284

Is it possible to have a data structure that is able to store different types?

A single data structure to store different types in a single variable.

Not asking for generics, some a dynamically typed data structure.

Is it possible?

Upvotes: 0

Views: 262

Answers (4)

Shaun
Shaun

Reputation: 4018

You could just use Object as the variable type.

Not sure exactly what you are after. I'd argue that, in Java, it's Generics that provide dynamic typing.

Upvotes: 2

MattC
MattC

Reputation: 12327

Technically since everything inherits from Object, coupled with autoboxing for primitives yes you can. Although without casts and heavy use of "if X instanceof Y" statements, you'll have a sticky time.

Upvotes: 2

SingleShot
SingleShot

Reputation: 19131

I'm not 100% sure what you are asking, but all Java collections support un-typed data. For example:

List dataStructure = new LinkedList();

dataStructure.add(new Long(5));
dataStructure.add("Hello");
dataStructure.add(new BankAccount());

Upvotes: 3

David Berger
David Berger

Reputation: 12803

Yes. All the data structures in the standard library end up using generics with type-erasure. Something like:

ArrayList<Object> dynamicData = new ArrayList<Object>();

should do just fine. Just remember, you will have to cast after you pull objects out of the structure.

Upvotes: 4

Related Questions