Code Comments
Programming Forum and web based access to our favorite programming groups.I am learning Java,but I happened to read a book about C++.I find in
C++,you can use <template T>.
e.g.
<template T>
void swap(T a,T b)
{
T temp=a;
a=b;
b=a;
}
T can be char,int ect.
So whatever I want to swap int or char or something else,I only need to
write the codes once.
Can Java do this?
Post Follow-up to this messageHi, Genericity (template classes) was just added in the new java version J2SE 5.0 http://java.sun.com/j2se/1.5.0/docs...s.html#generics HTH Regards, Giovanni <iherage@gmail.com> wrote in message news:1117636888.757651.187950@o13g2000cwo.googlegroups.com... >I am learning Java,but I happened to read a book about C++.I find in > C++,you can use <template T>. > e.g. > <template T> > void swap(T a,T b) > { > T temp=a; > a=b; > b=a; > } > T can be char,int ect. > So whatever I want to swap int or char or something else,I only need to > write the codes once. > Can Java do this? >
Post Follow-up to this messageGiovanni Azua wrote: > Hi, > > Genericity (template classes) was just added in the new > java version J2SE 5.0 > > http://java.sun.com/j2se/1.5.0/docs...s.html#generics > > HTH > Regards, > Giovanni > > <iherage@gmail.com> wrote in message > news:1117636888.757651.187950@o13g2000cwo.googlegroups.com... > This will only do what you wanted if you make those reference parameters as in swap( T &a, T &b ) As Giovanni noted generics were added in JDK 1.5, but generics are not the same as C++ templates and will not work with the primitive types. The swap method also depends on pass by reference which is something that Java does not support (thank goodness). -- Dale King
Post Follow-up to this message
Show a Printable Version
Email This Page to Someone!
Receive updates to this thread
Powered by vBulletin
Copyright 2000-2006 Jelsoft Enterprises Limited.