tags:

views:

95

answers:

4

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?

+2  A: 

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.

Shaun
+4  A: 

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.

David Berger
How about just plain ArrayList?
Alex B
Checkers: Raw types are bad, m'kay. David: Type erasure is completely irrelevant here.
Tom Hawtin - tackline
The compiler complains if you use the bare type and useing List<Object> keeps it happy.
Aaron Maenpaa
@Tom It's not irrelevant, but I haven't justified mentioning it. It's relevant because the data-structures are implemented without reference to the generic type, i.e. it was my way of pointing out that the OP's goal is accomplished by simply telling the compiler to permit anything. It's not an important or necessary point, just interesting.
David Berger
+3  A: 

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());
SingleShot
+2  A: 

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.

MattC
Actually you'll have a sticky time *because* of casts and instanceof calls :P
MattC