Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

java equivalent of c++ template?

Status
Not open for further replies.

drewdaman

Programmer
Aug 5, 2003
302
CA
hello, was wondering if there is a java equivalent of a c++ template?
what i would like to do is to make a stack, but not be restricted to what i can push/pop on the stack (all the data will be the same on the stack, but i would like to be able to use teh same code for different objects).

thanks!
 
Generics (available in Java 5) are Java's version of templates.
 
If you want to put multiple object types into some kind of collections object, then you don't want generics/templates - you want a normal 1.4 style collection object - where you dump any kind of object into the collection, and handle the type casting yourself.

--------------------------------------------------
Free Database Connection Pooling Software
 
It sounds as if drewdaman wants several stacks, each intended to hold a different type of object, but none necessarily intended to hold different types at the same time. If that is the case, then using generics would be better than holding Objects, since you could have better type safety at compile time and you could avoid the unnecessary casts.

It seems that in Java 5, most of the collections use generics. I haven't done much reading on the exact reasons, but the natural assumption is that for the reason above they are more appropriate than the original method of just holding Objects.
 
hi guys.. thanks for the responses... the stack was just an example.. i have been using c++ lately and i guess i just think terms of c++ now! i havne't used java in many years.. and i need to brush up on it.. (and learn swing too!) and i was just curious about how this is done in java.
 
Most collections store things as Object (since all objects derive from Object), and then to get the right type back, you cast.

Java 1.5 (which is still in beta, yes? and most end users don't have JVMs for yet) introduced Java templates called "generics". It also introduced awful shortcuts for writing a loop through a container, and a lot more "normal" (C++ speaking) way of handling type safe enums. I think I'll like the changes when I migrate to 1.5, but untill then I think they take away from the original intent Java was after.

[plug=shameless]
[/plug]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top