Generic classes of generic classes?

Started by
5 comments, last by TheChubu 11 years, 6 months ago
Hi! It is possible to make a generic class that contains an attribute that can be either an object of the same generic class or some other type?

Say, generic class X has the attribute A, that attribute A can be either an object of generic class X (that we don't know its attribute A type yet) or a string, depending on certain conditions that are evaluated at runtime.

In my quest for implementing a quad tree, I've reached the point where I can generate it but I now want to store something on it, thus the need of generics. Ideally, in my quad tree, only the leaves will store something, the rest of the nodes won't.

I've implemented it in a way I'm only using one class "QuadTree" for the whole thing. The simple solution is just add an attribute "storedThing" of type objT, initialize it with "null" if its a root or mid child node, if its a leaf I assign to it the object I'm storing and be done with it. But, I thought that I could use the child node attributes themselves to store things with some generics magic.

So my quadtree its like:
class QuadTree
{
QuadTree Norheast, Southeast, Southwest, Northwest;
}

Each QuadTree object has four more QuadTree objects, until I reach the leaves, then I initialize those with null, and the time to store something comes. My idea was that those variables could be more nodes of class QuadTree<T> or objects that I want to store, depending on the location of the node that I'm creating. Something like:

if (nextNodeisNotLeaf) //Next level on the tree is not the last.
{
// Each attribute is a new QuadTree object, and the process repeats.
NE = new QuadTree();
SE = new QuadTree();
SW = new QuadTree();
NW = new QuadTree();
else
{
// Its a leaf, so each attribute is of the class type I want to store.
NE = new objT();
SE = new objT();
SW = new objT();
NW = new objT();


But I don't know how to do that. Its like a recursive thing, except I need to unroll the whole thing on a single line if I want to do anything! (ie, quad tree of 4 levels: root.NE = quadtree<quadtree<objectToStoreType>>; and what if I want to make a 5 level quad tree later on the program? Can't modify the class's source on runtine! ).

I wan't to decide what type each object instance of that class is going to store. But can't figure it out how to do it all in a single generic class...

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

Advertisement
Let's start with the most profound -and hard to follow- advice for software developers: KISS. In that spirit you have already described your simple solution, so I would run with that.

Just for the challenge of it, let's explore the complex solution. Keep in mind that I strongly advice against this unless you have really compelling reasons to want to save on a single extra property of the QuadTree class.

Basically you want your node references to hold either a QuadTree class reference or a reference to your target class. The rules of inheritance state that in that case both must have some common super class or common interface, otherwise it will never work. So if you really really want to do this, you can have your target class implement a QuadTree interface. This seems a very intrusive way (as seen from the objects you want to store) to implement it, but it works.

There is an alternative solution. Use the one common superclass that all classes have: Object. Each node NE, NW, SE, SW is just of type Object. You can still use generics to restrict what goes into and comes out of the quad tree, but you use it in the getter and setter methods. Now inside the QuadTree you will have to do a lot of instanceof comparisons to find out what a node is (ugh!), but it should work as well.

The simple solution is just add an attribute "storedThing" of type objT, initialize it with "null" if its a root or mid child node, if its a leaf I assign to it the object I'm storing and be done with it.
To be honest, I would probably just do that.

To store the data solely in the leaf nodes only then something like this could be done:

First, define an interface that allows for traversal of the tree plus detection and access to any stored data/ This interface lets us use the quad tree without really caring about the particular node implementation:
public interface IQuadTreeNode<T> {
public boolean hasData();
public T getData();

public IQuadTreeNode<T> getUp();
public IQuadTreeNode<T> getDown();
public IQuadTreeNode<T> getLeft();
public IQuadTreeNode<T> getRight();
}


Now we can implement this interface for inner nodes which only need to store linkages to surrounding nodes but don't need to store data. Also note that the surrounding nodes are referenced via the above interface. This lets us wire up nodes to either another inner node or a leaf node:

public class QuadTreeInnerNode<T> implements IQuadTreeNode<T> {

private IQuadTreeNode<T> up, down, left, right;

@Override
public boolean hasData() {
return false;
}

@Override
public T getData() {
return null;
}

@Override
public IQuadTreeNode<T> getUp() {
return up;
}

@Override
public IQuadTreeNode<T> getDown() {
return down;
}

@Override
public IQuadTreeNode<T> getLeft() {
return left;
}

@Override
public IQuadTreeNode<T> getRight() {
return right;
}

}


Also implement for leaf nodes, which don't store linkages, only data:

public class QuadTreeLeafNode<T> implements IQuadTreeNode<T> {

private T data;

@Override
public boolean hasData() {
return true;
}

@Override
public T getData() {
return data;
}

@Override
public IQuadTreeNode<T> getUp() {
return null;
}

@Override
public IQuadTreeNode<T> getDown() {
return null;
}

@Override
public IQuadTreeNode<T> getLeft() {
return null;
}

@Override
public IQuadTreeNode<T> getRight() {
return null;
}

}
Why not something like this then ???


public interface Element<T> {}

public interface Node<T> extends Element<T> {
Element<T> northEast();
Element<T> southEast();
Element<T> southWest();
Element<T> northWest();
}

public interface Leaf<T> extends Element<T> {
T data();
}
Thanks for your answers! Took me a while to understand all of your solutions (never thought about using Object as a type).

It looks like a common interface would do the trick nicely (had to look up interfaces since I'm kinda beginning in Java specifics). Anything that has to go inside the QuadTree has to implement that interface so the QuadTree knows how to handle it. And something similar could be made for the three different nodes the tree is going to deal with (root, middle, leaf).

The root and middle nodes would add to the inherited QuadTree class the four node references NE, SE, SW, NW (plus irrelevant things) while the leaf node would just add the data property. That would split the three constructors I'm using in a single class into three classes that inherit the common portion of QuadTree (I think it would also clarify the source code a little).

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?

By the way, I'm not sure what the QuadTree could do with the data. I had thought about just storing (ie add(data, posx, posy)) something and retrieve something (ie data = retrieve(posx, posy)). The main program has to know what positions its handling, or at least just ask blindly (give some coords to the quadtree and let it show whats in there).

The quadtree should do something else besides that? I'm thinking that since im handling squares, asking it what is located inside the bounds of an arbitrary square and let the quadtree retrieve all the data inside it. It would simplify searching for things on a specific area. Or just handle the data, without positions, and let the quadtree determine if it exists, and what is its position. It shouldn't be too hard to implement (I guess). The node traversing is the hardest part as I see it, everything else is just checking coords against squares.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator


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.
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.
Ah I see. Read a little about upcasting and downcasting, Wasn't getting if by "up" it meant the super-class or the sub class.

It shoulnd't be that hard I guess. I know for a fact exactly what nodes will have data, and since that data is a generic type, I could downcast the leaf node's attributes to the generic type I entered into the quadtree and I should get what I want.

That said, having all sub nodes of type Object would be a lot of hassle as you said. Creating them wouln't be a problem, but traversing through them would imply a lot of downcasting the Object NE,SE, etc to access their QuadTree properties each time I need to pass through one of them. In short, simplified types but over complicated methods.

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.
Yep, looks like it. Heh, it would have been interesting to try to make it by using unions.

Thanks for your answers! I thought that by just using the generic type on the nodes (ie QuadTree<T> {T NE,SE,SW,NW} ) I could get something working (and I just lacked the middle mojo to make it work) but its not the case it seems.

I'm going with the inheritance/interface way, looks like the "prettiest" one and I'll avoid having to overload the constructor two times to get the nodes I want.

"I AM ZE EMPRAH OPENGL 3.3 THE CORE, I DEMAND FROM THEE ZE SHADERZ AND MATRIXEZ"

My journals: dustArtemis ECS framework and Making a Terrain Generator

This topic is closed to new replies.

Advertisement