I’m writing a method that doubles the size of the data in every node in a tree. I think I have the algorithm down for writing it, but I’m having trouble figuring out how to multiply a generic type by 2.
So essentially I want to take a data that is type T and convert it to an integer, multiply it by two, and store it as type T. I’ve played around with some options but none have worked. Any help on how I should do this would be helpful. If you need any other info let me know. Thanks.
Because of type erasure, you cannot do this directly. One approach is is to define a generic interface for objects that “know” how to double themselves:
Then you can make each node (that knows how to double itself) implement the
Doublerinterface.There are other approaches (factory methods, factory objects, passing around
Class<T>instances, etc.) that might work just as well (or better). But the one thing you can’t do is create an instance of a generic type in code that just knows the generic type and nothing else.