CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Apr 2001
    Posts
    140

    Add a double to a Vector?

    How does one add a double to a vector?

    Many thanks in advance

  2. #2
    Join Date
    Jul 2006
    Posts
    29

    Re: Add a double to a Vector?

    Don't know if this is what your looking for but:

    Vector vector = new Vector();
    vector.addElement(new Double(value));

  3. #3
    Join Date
    Apr 2001
    Location
    South Africa, Jo'burg
    Posts
    680

    Re: Add a double to a Vector?

    Hi,

    If you are using JDK 5 or above there is an easier way of doing. The way that smbelow suggested works fine except that you will need to cast the object you get out of the Vector to a Double before you can use it, and if you want a double primitive it will take you another step to get that from the Double wrapper object.

    With JDK 5 and above generics and autoboxing make task like this easier, there is a limitation though, you need to know that all of the objects stored in the Vector will be of type Double (which is normally case since you generally know what you are adding to your collections). You declare your Vector like this:
    Code:
    // Tell java that you will be storing Double objects in the Vector using generics
    Vector<Double> vect = new Vector<Double>();
    
    // Using autoboxing you can add primitive double objects to the Vector without having to wrap them first (it)
    double dIn = 100d;
    vect.add(dIn);
    
    // And with generics and auto-unboxing you can simply retrieve the object as a primitive without any casts
    
    double dOut = vect.get(0);
    So this approach reduces a number of steps that were required before and has the added advantage of type safety, you can only add Double objects to the list now, you will get a compile time error if you try and add anything else, where before you would get a runtime error when you try and cast a String to a Double.

    Hope This Helps
    Last edited by Bnt; November 2nd, 2006 at 03:25 AM.
    Byron Tymvios

    Please use [ CODE ] and [/ CODE ] tags when posting code! See THIS on how to use code tags.

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured