Results 1 to 4 of 4
  1. #1
    azalea is offline Member
    Join Date
    Oct 2011
    Posts
    12
    Rep Power
    0

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

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

    Default 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:

    Java Code:
    List<Number> seq = new ArrayList<Number>();
    then just do

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

  3. #3
    azalea is offline Member
    Join Date
    Oct 2011
    Posts
    12
    Rep Power
    0

    Default Re: Arithmetic with Generic Types

    Oh perfect. Thanks!

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,585
    Rep Power
    12

Similar Threads

  1. comparable interface, generic types
    By dylandrop in forum New To Java
    Replies: 3
    Last Post: 04-16-2011, 08:45 PM
  2. generic and different enum types
    By vojtab in forum New To Java
    Replies: 0
    Last Post: 11-08-2010, 06:11 PM
  3. Help with comparing generic types
    By repairmanjack in forum New To Java
    Replies: 4
    Last Post: 09-22-2009, 07:41 AM
  4. generic types
    By jon80 in forum New To Java
    Replies: 6
    Last Post: 06-12-2009, 11:29 PM
  5. Can generic types implement an interface?
    By jdgallag in forum New To Java
    Replies: 3
    Last Post: 10-30-2008, 05:07 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •