[java] What does a template in C++ equivalent to in Java

Started by
12 comments, last by casper 24 years, 1 month ago
Hello all, I need to know what Java uses for templates because I definitely need that type of functionality. Thanks, Casper
...for over a thousand years the Jedi Knights have been the guardians of peace and justice..before the dark times..before the EmpireCasper..
Advertisement
This isn''t exactly an answer to your question, but this may be useful. Everything in Java inherits from Object. This inheritance is implicit, and exists whether you tell it to explicitly or not.

Therefore, you can use some of the functionality for a template by using Object. All of the classes for storing information use this, ie Vector. You might want to look at java.util.Vector to see how you can effectively use Object.

This may not directly answer your question, but might get you on a useful track.

Thanks,
Shaun
I wanted to add this caveat to what I just said. All of the basic types in java (ie float, double, int, boolean) do not inherit from Object. Rather there are wrappers that enclose them as objects (ie Float, Double, Int, etc).
It would''ve been nice for you to explain what a template was, instead of assuming everyone knows c++. From what i gather reading posts about c++ templates are like interfaces. Tell me if that''s not true cuz i want to know what a c++ template is.
No, Java doesn''t support template like behaviour yet. There was an article few months back in Dr.Dobb''s Journal about Generics (or something) that are going to be introduced to Java language specification at some point. But until that you will just have to either revert to the Object paradigm or do search & replace to make containers or algorithms for different types.

The "everything is inherited from Object" paradigm that sckime is talking doesn''t really cut it as a replacement for templates for several reasons:

1. There is no compile time type checking for the casts you need to perform when e.g. getting an element from java.util.Vector. This is a major consern if you are making a product and want to make the product as robust as possible before it even reaches testing as testing costs money and runtime type checking requires extensive testing.

2. You have to know what elements you are storing in the generic Object references. And as a consecuence from this it is really hard to efficiently store different types into same container that uses the Object paradigm. Sure you can use the instanceof operation, but that is slow, slow, slow. And it also adds more possible execution paths to the code which in turn adds more test cases to be tested.

3. Performing some operations with/to these Object objects is a pain as you will have to make a new interface or baseclass that introduces the operation to the class and then cast every stored object to the interface/baseclass.

4. Last, but not least (as we are talking about Java game development here) the extensive type casting needed in the Object paradigm approach is quite slow in Java. I once did a simple A* search tree implementation that tried to solve a simple 3x3 slide puzzle and got a HUGE (around 1.5 times) performance increase just by writing specialized containers (without using the java.util.Vector as a base class) for the few key objects that I needed to store.
-Pasi Keranen
quote:Original post by Jim_Ross

It would''ve been nice for you to explain what a template was, instead of assuming everyone knows c++. From what i gather reading posts about c++ templates are like interfaces. Tell me if that''s not true cuz i want to know what a c++ template is.


Nope, C++ template is not an interface. Template is, well it is a sort of a class template.

When you define a template class you can leave the handled datatype(s) open and then define it upon compiling. E.g. if I wanted to make a Vector template I would use a special tag (datatype) in the place of the datatype I wanted to handle and just define that a vector holds a datatype array and can add a datatype "objects" and get a datatype "object" from the array. Then when I want to have a vector for e.g. MyOwnClass objects I just construct the Vector template and tell the template that the datatype is going to be MyOwnClass. And when I compile the code the compiler creates a new Vector class definition from the template and replaces all references to datatype with MyOwnClass.

You can "emulate" this with Java by writing a file e.g. Vector.template and writing the code there using datatype as the "object" type you are going to handle. Then when you need a Vector in your app, you just copy the Vector.template to some other folder, rename it to e.g. VectorInt.java and search-replace every datatype word with int. And presto! You have a Vector capable of handling integers.

Actually you could write a small utility to do this for you, hmm... Smells like a small project idea...
-Pasi Keranen
Templates are available on the Java platform. Just look at the Pizza compiler / the Kiev Language. I haven''t looked at the source code, hence I don''t know yet how it is implemented. Probably some kind of preprocessor.

===
David Teller
Editions Vigdor
http://www.vigdor.com
ddt@vigdor.com
David.Teller@ens-lyon.fr
http://www.ens-lyon.fr/~dtelle


Les Mots appartiennent a ceux qui savent s''en servir.
Javanerd''s explanation of templates, although he states that they are not templates, sounds very much like they are similar to templates. Interfaces are agreements that all subclasses shall obey a certain standard, like a template for a class. It seems like making an Object interface, then subclassing it with the types that you need and typecasting should solve all your template problems.

On a side note, I don''t see why one would "need the ''functionality''" of dynamically typed data. I get that ''feature'' all the time in scripted languages like php. It is definately not needed, and in fact, it is a hinderance sometimes.
Typecasting is quite as good as templates. Templating is a compile time effect, not a dynamic effect. Essentially to get the same kind of functionality out of java right now, you need to write a wrapper around a Object referencing data structure to handle the data passing properly. So you start maintaining at least two separate objeccts for one objects worth of functionality.

You still seem unclear on the concept of templates, so I will attempt to further clarify. (Forgive the syntax.)

Let's say I want a Stack class that I will only pit Sprite objects into. With C++ templates I would do something like:

template <class T> class Stack {  Push(T * element);  T * Pop();  T * Peek();};  

And declare like:
Stack<Sprite> sprite_stack;
Which would create an object that has Push(Sprite *) method, Sprite * Pop() method, etc.

In Java I'd do something like:
class Stack_impl {  Push(Object element);  Object Pop();  Object Push();}class SpriteStack {  Push(Sprite element);  Sprite Pop();  sprite Peek();}  

And then I'd have to either inherit or encapsulate SpriteStack from Sprite in order to use the Object bound Stack_impl class. This isn't too bad for just one pair, but you can see the extra annoyance it would be to maintain a SpriteStack and a PolygonStack and a SpriteStackStack vs. simply instantiating a Stack<Sprite>, Stack<Polygon>, Stack<Stack<Sprite>>.

This post editted due to severe html butchering.

Edited by - SiCrane on 3/13/00 12:24:05 PM
quote: Original post by SiCrane

Typecasting is quite as good as templates. Templating is a compile time effect, not a dynamic effect. Essentially to get the same kind of functionality out of java right now, you need to write a wrapper around a Object referencing data structure to handle the data passing properly. So you start maintaining at least two separate objeccts for one objects worth of functionality.

(some text snipped)

And then I'd have to either inherit or encapsulate SpriteStack from Sprite in order to use the Object bound Stack_impl class. This isn't too bad for just one pair, but you can see the extra annoyance it would be to maintain a SpriteStack and a PolygonStack and a SpriteStackStack vs. simply instantiating a Stack, Stack, Stack>.


I'll have to disagree with you on this. Runtime typecasting is not as good option as compile time type checking.

When you store something in e.g. java.util.Vector it will be stored and retreived as an Object reference. When you need to cast that to your own class (e.g. the Sprite object you used). You have to do

Sprite mySprite = (Sprite) mySpriteVector.firstElement();


And this is error prone. Of course you can catch the invalid cast exception, but in order to even get the exception you will have to have a test case for that particular situation. This takes us back to the "what you can test with compiler is less work when testing the system later on".

No, in your example case you can't inherit from the stack that uses objects. If you try:

class SpriteStack extends Stack_impl {
Push(Sprite element);
Sprite Pop();
sprite Peek();
}


The compiler will give you error that you can't override a method by changing the return type. Even if you could override it would still leave the Push( Object object ) method visible in the SpriteStack class and that would allow you to add objects of any type in to the stack.

You can encapsulate the Stack_impl inside SpriteStack but that (as you point out) requires writing a new class by hand for every type you want to handle. It also adds one more invokation for each call you make to the methods and as we are talking game programming here, that is bad news for the performance.

As you said "Templating is a compile time effect, not a dynamic effect" and that is its strength. The resulting code is typechecked on compile time and the resulting code is faster (as you don't need to do any type checking/casting on runtime). I'm quite eager to get the templates into Java standard. It really just requires a syntax to specify the template usage and a compiler specification on how it interpretes that syntax and generates code. No changes to the Java bytecode itself are needed.

But until that time, we just have to write those copy-paste containers for every object type by hand or use the inferior "everything is inherited from Object" paradigm.

Edited by - javanerd on 3/14/00 6:46:41 AM
-Pasi Keranen

This topic is closed to new replies.

Advertisement