It depends, as Verik said you could upcast it all to Object but then you have to somehow know, or test for, the type information.Now, are all of you telling me that I can't do what I want to do by solely using generics and a single class? I need inheritance/interfaces in the middle?
Essentially you need some way to express the fact that a node can reference either another node or a piece of data. That means you either:
- Abstract the difference behind an interface and handle uniformly through that interface.
- Use data to describe the difference between node types, so give all nodes an optional reference to some data and maintain an invariant that we will only set that reference if the node is a leaf-node.
- Give up type information with a lowest common denominator "Any" type (e.g. Object in Java, or void* or any<> in C++) and rely on downcasting type information back in later on.
- Use a discriminated union and model precisely the "either-node-or-userdata" concept. Discriminated unions aren't in Java's core language though.
- Specialise/overload the class implementation - Java can't really do this.
Different languages make different options more or less practical. In Java I would say that the first and second options in that list are the most reasonable.