Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

"templated" class

  Asked By: Jada    Date: Dec 08    Category: Java    Views: 709
  

I'm trying to make a "C++ templated"-style of Java class. For
instance, I want to write eight methods in my class that will
translate an array being passed into the class (I can't change that
I'll have to initially deal with an array) which is initially an
array of one of the eight primitive types into an object array, then
pass that object array around in my methods.

For instance, I'd like to use the following method:

public String toString(Object a[])
{
StringBuffer stringster = new StringBuffer();
stringster.append("{");
for (int i = 0; i < a.length; i++)
{
stringster.append(a[i]);
if (i < a.length-1) stringster.append(", ");
} //end for loop
stringster.append("}");
return stringster.toString();
} //end tostring method

This method would work equally well on an array composed of floats,
strings, characters, etc. I've looked at changing the initial array
into an ArrayList, but I can't figure out how to change it without
using something like Integer.toInt, Float.toFloat, etc.

Is there anything in Java like the templated classes of C++? Have I
just been missing something very obvious? (Hopefully, I've been
missing something very obvious.) ;)

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Wilbur Hall     Answered On: Dec 08

Upto java  1.4 you can only hold reference types  in the
Collection/Container classes  so you are stuck with
either using arrays or using the wrapper classes for
the primitives. This has been remedied somewhat in
Java 1.5 with the introduction of generics. The syntax
will be familiar if you know templates in C++.

ie.

Stack<int> col = new Stack<int>();
col.add(2);

note that this is not technically equivalent to it's
C++ counterpart in that it is not compiled to a
different type of Stack rather it is more like an
instruction for the compiler to disallow entries to
the above Stack that are not Integers. Note I said
Integers and not int's because the second line above
is "translated" into col.add(new Integer(2));.

For a more complete description of Generics in java go
to:

http://www.ociweb.com/jnb/jnbJul2003.html

 
Didn't find what you were looking for? Find more on "templated" class Or get search suggestion and latest updates.




Tagged: