Jump to content

  • Log In with Google      Sign In   
  • Create Account

14 years ago on June 15th Gamedev.net was first launched! We want to thank all of you for being part of our community and hope the best years are ahead of us. Happy birthday Gamedev.net!

#Actualdmatter

Posted 27 September 2012 - 07:42 AM

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?

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.

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.

#1dmatter

Posted 27 September 2012 - 07:41 AM

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?

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.
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.

PARTNERS