For Programmers: Free Programming Magazines  


Home > Archive > Java Help > June 2005 > C++ has the key word <template>.Do Java have something alike?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author C++ has the key word <template>.Do Java have something alike?
iherage@gmail.com

2005-06-01, 4:01 pm

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?

Giovanni Azua

2005-06-01, 4:01 pm

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...
>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?
>



Dale King

2005-06-02, 4:01 am

Giovanni Azua wrote:[color=darkred]
> 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 )
[color=darkred]

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.
[color=darkred]

The swap method also depends on pass by reference which is something
that Java does not support (thank goodness).

--
Dale King
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com