Arithmetic with Generic Types

Hi All,

I am new to java, and I'm coding a class with generic type <T>,

in which I have a variable seq = new ArrayList<T>();

I am interested in doing arithmetic on the elements of seq,

in particular I would like to do the following:

double temp = seq.get(i) * Math.pow(2, t);

Now, given that seq.get(i) returns a variable of type <T>,

I wrote a cast function:

@SuppressWarnings("unchecked")

public static <T> T cast(Object o) {

return (T) o;

}

and I do the following:

double temp = (cast<Double>(seq.get(i))) * Math.pow(2, t);

But I get syntax error!

If I use "cast<double>...", I get Syntax error on token(s), misplaced construct(s),

If I use "cast<Double>..." (I actually thought with generic types I have to use upper-case), I get Double cannot be resolved to a variable.

What I am doing wrong here?

All this generic coding is because I may get a sequence of integers, doubles, long doubles, etc. and I thought it would be a waste of memory to use say long doubles for the case where the program is to act on integers.

Thanks,

- Azalea.

Re: Arithmetic with Generic Types

If the contents of the array are all numbers (which they would have to be to have *Math.pow(2,t) make any sense) then you could declare the array as such:

Code:

`List<Number> seq = new ArrayList<Number>();`

then just do

Code:

`double temp = seq.get(i).doubleValue() * Math.pow(2, t);`

Re: Arithmetic with Generic Types

Re: Arithmetic with Generic Types