I am working on a project to create a network simulator. The networks I am simulating are hierarchical networks. I am using a k-ary tree data structure, with some extra methods to simulate and perform some analysis of the networks.
So far, I have a generic k-ary tree data structure that accepts generic types, it works fine. The problem is that the tree nodes can only seem to be of one type. For instance, if I declare the tree with type String the nodes must all be String objects.
However, since I am trying to model a computer network (or any network), some nodes might have to be server objects and some nodes might be host objects, or even router object etc...
I want my heterogeneous tree's nodes to have some server objects and some mobileDevice objects...
I am not finding too many answers to this on Google, and it seems to be testing my creativity. I do know of an abstract syntax tree builder called ANTL3R or something, it supposedly can utilize heterogeneous trees, but my tree is for networks, not compilers.
The solution to this is to define an interface
that all nodes of the tree must implement. Then you can declare your tree to store data of that type.
public interface ComputerComponent {
String getName();
ComponetType getType();
...
}
Tree<ComputerComponent> network;
The other alternative (not recommended) is to declare it to be Tree<Object>
. Then you can store anything in it but you lose all type checking capabilities and will end up having to use instanceof
and casts to use the data you retrieve.