Converting Object Arrat to double array

public double average(Object ... object)
          double avg=0;
          int count=1;
          for (double d: object)
               count++;
                avg +=d;
          return (avg/count);
     }I wanted this code to get compiled with out making much changes(I do not want to change the parameter type of the method).I am gonna pass a double array as an argument to this method.And how could I test that the argument is a double array.

Pravin
I don't know if this is exactly what you want, but it is as close as I could make it to your post, and it compiles.    public double average(Object ... objects) {
        double avg = 0;
        int count = 1;
        for (Object d : objects) {
            count++;
            try {
                avg += (Double) d;
            } catch (java.lang.ClassCastException e) {
                System.out.println(e.toString());
                System.out.println("Element No." + count +
                        "is not a valid double.");
        return (avg / count);
    }Please elaborate if you need something more.
db

Similar Messages

  • How can i convert object to byte array very*100 fast?

    i need to transfer a object by datagram packet in embeded system.
    i make a code fallowing sequence.
    1) convert object to byte array ( i append object attribute to byte[] sequencailly )
    2) send the byte array by datagram packet ( by JNI )
    but, it's not satisfied my requirement.
    it must be finished in 1ms.
    but, converting is spending 2ms.
    network speed is not bottleneck. ( transfer time is 0.3ms and packet size is 4096 bytes )
    Using ObjectOutputStream is very slow, so i'm using this way.
    is there antoher way? or how can i improve?
    Edited by: JongpilKim on May 17, 2009 10:48 PM
    Edited by: JongpilKim on May 17, 2009 10:51 PM
    Edited by: JongpilKim on May 17, 2009 10:53 PM

    thanks a lot for your reply.
    now, i use udp socket for communication, but, i must use hardware pci communication later.
    so, i wrap the communication logic to use jni.
    for convert a object to byte array,
    i used ObjectInputStream before, but it was so slow.
    so, i change the implementation to use byte array directly, like ByteBuffer.
    ex)
    public class ByteArrayHelper {
    private byte[] buf = new byte[1024];
    int idx = 0;
    public void putInt(int val){
    buf[idx++] = (byte)(val & 0xff);
    buf[idx++] = (byte)((val>>8) & 0xff);
    buf[idx++] = (byte)((val>>16) & 0xff);
    buf[idx++] = (byte)((val>>24) & 0xff);
    public void putDouble(double val){ .... }
    public void putFloat(float val){ ... }
    public byte[] toByteArray(){ return this.buf; }
    public class PacketData {
    priavte int a;
    private int b;
    public byte[] getByteArray(){
    ByteArrayHelper helper = new ByteArrayHelper();
    helper.putInt(a);
    helper.putInt(b);
    return helper.toByteArray();
    but, it's not enough.
    is there another way to send a object data?
    in java language, i can't access memory directly.
    in c language, if i use struct, i can send struct data to copy memory by socket and it's very fast.
    Edited by: JongpilKim on May 18, 2009 5:26 PM

  • Converting object wrapper type array into equivalent primary type array

    Hi All!
    My question is how to convert object wrapper type array into equivalent prime type array, e.g. Integer[] -> int[] or Float[] -> float[] etc.
    Is sound like a trivial task however the problem is that I do not know the type I work with. To understand what I mean, please read the following code -
    //Method signature
    Object createArray( Class clazz, String value ) throws Exception;
    //and usage should be as follows:
    Object arr = createArray( Integer.class, "2%%3%%4" );
    //"arr" will be passed as a parameter of a method again via reflection
    public void compute( Object... args ) {
        a = (int[])args[0];
    //or
    Object arr = createArray( Double.class, "2%%3%%4" );
    public void compute( Object... args ) {
        b = (double[])args[0];
    //and the method implementation -
    Object createArray( Class clazz, String value ) throws Exception {
         String[] split = value.split( "%%" );
         //create array, e.g. Integer[] or Double[] etc.
         Object[] o = (Object[])Array.newInstance( clazz, split.length );
         //fill the array with parsed values, on parse error exception will be thrown
         for (int i = 0; i < split.length; i++) {
              Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
              o[i] = meth.invoke( null, new Object[]{ split[i] });
         //here convert Object[] to Object of type int[] or double[] etc...
         /* and return that object*/
         //NB!!! I want to avoid the following code:
         if( o instanceof Integer[] ) {
              int[] ar = new int[o.length];
              for (int i = 0; i < o.length; i++) {
                   ar[i] = (Integer)o;
              return ar;
         } else if( o instanceof Double[] ) {
         //...repeat "else if" for all primary types... :(
         return null;
    Unfortunately I was unable to find any useful method in Java API (I work with 1.5).
    Did I make myself clear? :)
    Thanks in advance,
    Pavel Grigorenko

    I think I've found the answer myself ;-)
    Never thought I could use something like int.class or double.class,
    so the next statement holds int[] q = (int[])Array.newInstance( int.class, 2 );
    and the easy solution is the following -
    Object primeArray = Array.newInstance( token.getPrimeClass(), split.length );
    for (int j = 0; j < split.length; j++) {
         Method meth = clazz.getMethod( "valueOf", new Class[]{ String.class });
         Object val = meth.invoke( null, new Object[]{ split[j] });
         Array.set( primeArray, j, val );
    }where "token.getPrimeClass()" return appropriate Class, i.e. int.class, float.class etc.

  • How do i convert an image object to a byte array ?

    Hi
    how do i convert an image object into a byte array
    early reply apperciated

    Oh sorry my method and the other method need to have the pixels from the Image passed to them which you get my using pixelgrabber:
    //create width and height variables from image
              int w = img.getWidth(this);
              int h = img.getHeight(this);
              //retrive picture from image
              int[] pix = new int[w * h];
              PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pix, 0, w);
              try{ pg.grabPixels();
              } catch (InterruptedException ioe) {
                   System.err.println("Interrupted");
              if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
              System.err.println("image fetch aborted or errored");
              }

  • How do I Convert an "Object" to a "double"?

    Can anyone please tell me how to convert an "Object" to a "double"? Typecasting does not work.

    Do you want to convert any object at all to a double, or only particular kinds of objects? My guess is that you don't really need to convert a File or a JButton to a double, you have some kind of an object that really contains some sort of double information and you want to get it out. More information would help.

  • How do i convert a double array (with spaces and tabs) to a string?

    Hi
    In our files, we have a mixture of spaces and tabs as a delimeter. How do I convert a double array into a string?
    Thank you.

    Not sure about the last part of your question.
    The Search and Replace pattern can be better than the simple Search and Replace string when you have to do complex searchs, such as detecting multiple spaces.
    Have a look at the attachment.
    CC
    Chilly Charly    (aka CC)
             E-List Master - Kudos glutton - Press the yellow button on the left...        
    Attachments:
    ReplaceSpaces.vi ‏27 KB

  • Error in converting double to double array

    Iam getting a problem while coverting the values of a table to double array local variable . while the values r getting from the resultset using while(rs.next())
    all the values have to store in the double array.please give me solution to this problem.

    Show us your code and the problem you are facing.

  • Vectors : Converting to double[ ] array

    Hello,
    I have a vector which I know consists of double values only. I am trying to create an array of double from this vector but am having some difficulty.
    Firstly if I try this :
    double[] high = (double[])datavector.high.toArray(new double[0]);JBuilder reports :
    'Cannot find method toArray(double[])'
    But if I try this :
    Double[] high = (Double[])datavector.high.toArray(new Double[0]);It works.
    So from this I assume 'Double' is not equal to 'double'
    The trouble is I require 'double[ ]' and NOT 'Double [ ]'.
    Casting Double as (double) does not work... so how do I get double[] from my original vector ?
    Many thanks
    Kerry

    double[] d = new double[v.size()];
              int i = 0;
              for(Iterator<Double> it = v.iterator(); it.hasNext();)
                   d[i++] = (double)it.next();
              just declare the double array to be the size of the vector, then loop thru and populate the array one at a time
    ~Tim

  • Howto when i have very very large double array

    I have code my program about document retrieval.
    I create double array in size [10000]x[8000] for keep value for calculte someting in only memory (about metrix operation).
    I have set parameter to heap memory size at 1024m but it not enough, it has exception out of memory.
    I use Notebook that have RAM 1G. Is this cause for exception?
    Please help me to lead solution for my case.
    Thank you.

    anurag.kapur wrote:
    A couple of points:
    1. Your notebook has 1 GB of RAM and you are allocating 1024 MB (=1 GB) to the JVM heap, which is not possible, as you need some space for running various other Operating System processes as well.This is a good point. There are also things in the JVM itself other than the Java object heap that need space. Thread stacks, loaded classes, native libraries, etc.
    2. Why have you allocated 1024 MB to the JVM heap? Did you choose any random number (obviously with some degree of educated guess)?
    Your array size is 10000 * 8000 = 8 * 10^7
    Thus total heap memory required = 8 * 10^7 * 4 Bytes [The int data type is a 32-bit signed two's complement integer]
    = 320 * 10^6 Bytes
    = 320 MBExcept that peterdog1234 said that the array was an array of doubles, at 8 bytes each, so about 640MB are needed for the array. If the algorithms allow the loss of range and precision, maybe the array could be an array of floats, not doubles. That would keep the array in about 320MB. That would help with the space requirements, but might be slower as all the operations will have to expand the floats to be operated on as doubles, then converted back to floats for storage in the array. But on some architectures that's not too bad.
    I would use -XX:+PrintGCDetails to see how the heap has been partitioned into young generation (fast allocation and collection) and old generation (relatively long-lived data). You might have to reshape the heap to have at least 640MB in the old generation, and then whatever you can fit as the young generation, leaving some of your 1GB for the rest of the JVM, other programs running on the box, the operating system, etc. Maybe "-Xms768m -Xmx768m -XX:NewSize=64m -XX:MaxNewSize=64m" would be a good compromise. That gives you a 768MB Java object heap, with 64MB in the young generation and 704MB in the old generation, leaving 256MB (1GB-768MB) for "other things". Whether that works depends on now many other long-lived Java objects you have. But -XX:+PrintGCDetails will tell you that, too.

  • Converting XML String to MessageElement array

    Hi,
    I am trying to call a .NET web service from my Java client. I used WSDL2Java to generate the java classes for calling the .NET web service. The generated classes to call the service expects an array of org.apache.axis.message.MessageElement objects. I have a string representing an XML document which looks like this:
    String xmlString = "<Results><Adjustments><Adjustment><RebuildAdjustmentID>16</RebuildAdjustmentID><IsBasicAdjustment>true</IsBasicAdjustment><AdjustmentType>stone/AdjustmentType><Title>External walls</Title></Adjustment></Adjustments></Results>"
    I have tried converting the string into an array of MessageElement objects by the following way:
    MessageElement[] m = new MessageElement[1];
    Document XMLDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(result2.toString())));
    m[0] = XMLDoc.getDocumentElement();
    However I keep getting the following message returned from the service:
    "Object reference not set to an instance of an object"
    I have tried a handful of ways but keep getting this same error. I have searched the web for hours looking for a solution to this problem without success so any help/ideas much appreciated,
    Thanks.
    Paul

    Any updates on this?
    I am facing a similar problem.

  • Most efficient way to strip nulls from a Double[] array?

    I'm trying to optimize performance of some code that needs to accept a Double[] array (or a List<Double>) and fetch the median of the non-null values. I'm using org.apache.commons.math.stat.descriptive.rank.Median to fetch the median after converting to double[]. My question is how I can most efficiently make this conversion?
    public class MathStatics {
         private static Median median = new Median();
         public static Double getMedian(Double[] doubles) {
              int numNonNull = 0;
              for (int i = 0; i < doubles.length; i++) {
                   if (doubles[i] != null) numNonNull++;
              double[] ds = new double[numNonNull];
              for (int i = 0; i < doubles.length; i++) {
                   if (doubles[i] != null) ds[i] = doubles;
                   System.out.println(ds[i]);
              return median.evaluate(ds);
         public static void main(String[] args) {
              Double[] test = new Double[] {null,null,-1.1,2.2,5.8,null};
              System.out.println(MathStatics.getMedian(test));
    I'm sure that the code I wrote above is clunky and amateurish, so I'd really appreciate some insight into how to make improvements. FWIW, the arrays will typically range in size from ~1-15,000 doubles.
    Thanks!

    There's no need to loop over the array twice
              int numNonNull = 0;
              double[] ds = new double[numNonNull];
              for (int i = 0; i < doubles.length; i++) {
                   if (doubles[i] != null) {
    numNonNull++;
    ds[i] = doubles;
                   System.out.println(ds[i]);
    Except that ds will have length zero, so you'll get a OutOfBoundsException every time you use it.
    As you're using Doubles rather than doubles, you can add the non-null values to an ArrayList and then convert it to an array at the end.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • I want to convert a String into an array of bytes

    I am working with telnet programming with java, where I want to convert login name and password of an online user in 'String' format to 'Bytes', plz help me. Which Input or Output Stream I can use

    Assuming you've got the username / password into a String object, you can convert it to a byte[] array using this method.
    String.getBytes();
    Look at the String API
    http://java.sun.com/j2se/1.3/docs/api/java/lang/String.html
    Hope that helps.

  • Convert JPA Query getResultList to Array

    I have been struggling with this problem for several hours now. All I have succeeded in doing is attempt every possible way to convert a List into an array and I just get errors.
         // create native SQL query
         Query q = em.createNativeQuery("SELECT * FROM Project p");
         // get and process the results
         List<Project> list = q.getResultList();
            Project[] retVal = new Project[list.size()];
         for (int i = 0; i < list.size(); i++)
             retVal[i] = list.get(i);
         }One would assume this to work, however this generates a ClassCastException, cannot convert Object to Project, oddly because as far as I can see everything in the code is strongly typed. I think Persistence fills the typed List with Object and not Project??
    So I tried:
    Project[] retVal = list.toArray(new Project[0]);This generates an ArrayStoreException.
    Finally I tried the basic, should generate x-lint warning:
    Project[] retVal = (Project[])(list.toArray());This also return ClassCastException, same reason as the first attempt.
    I want my WebService function to return a standard Project[] not the java.lang.List class. But it seems JPA queries only support getting a List. I have googled to no end for a solution. Help appreciated!
    Thanks.

    You are almost right, you can solve this two ways as below:
    First, use native query with result class reference.
    Second, use JPA query with createQuery method.
    Both the options should work, see code below:
    // First option, create native SQL query with result class reference.
    Query q = em.createNativeQuery("SELECT * FROM Project p",Project.class);
    // Second option, Create JPA Query.
    // Query q = em.createQuery("SELECT p FROM Project p");
    // get and process the results
    List<Project> list = q.getResultList();
    // Putting result to an array
    Project[] retVal = new Project[list.size()];
    list.toArray(retVal);*Cheers,
    typurohit* (Tejas Purohit)

  • How can I use a 1 double array for this

    I would like to use one double array where I am using 2 single arrays, can this be done?
    thanks
    import java.text.NumberFormat;
    import java.util.Locale;
    class Mortgage3
              public static void main(String[]argv)
              //Variables
              //allows for currency format
              NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US);
              double prin;                              
              double month_payments;
              double monthlyinterest;   
                    //standard integer
              int months;     
                    //array for the different interest rates
                    double[] interest = {0.0535,0.055,0.0575};
              //array for the different terms
                    int[] term = {7, 15, 30};
                    for (int i = 0; i < 3; i++)
              //values for the variables
              prin = 200000;        //principle amount of the mortgage
                    monthlyinterest = (interest[i] / 12);          //monthly interest
              months = (term[i] * 12);               //total amount of months in the 30 yr term
              //monthly payment calculation
              month_payments = (prin * monthlyinterest) / (1-Math.pow(1 + monthlyinterest, - months));           
              System.out.println("\n\n\t For a loan amount of " + formatter.format(prin));
              System.out.println("\t With an annual interest rate of " +interest[i] * 100+ "%,");
              System.out.println("\t your payments will be " +formatter.format(month_payments)+ " per month");
                    System.out.println("\t for a term of "+term[i]+ " years or " +months+" months.");
    }

    I would like to use one double array where I am using 2 single arrays, can this be done?It can, but why not write a Rate class or other data structure more suited to the purpose?

  • Hi, how can i break the value for a row and column once i have converted the image to the array?????​??

    Hi, I would like to know how can i break the value for a row and column once i have converted the image to the array. I wanted to make some modification on the element of the array at a certain position. how can i do that?
    At the moment (as per attachhment), the value of the new row and column will be inserted by the user. But now, I want to do some coding that will automatically insert the new value of the row and the column ( I will use the formula node for the programming). But the question now, I don't know how to split the row and the column. Is it the value of i in the 'for loop'? I've  tried to link the 'i' to the input of the 'replace subset array icon' , but i'm unable to do it as i got some error.
    Please help me!
    For your information, I'm using LABView 7.0.

    Hi,
    Thanks for your reply.Sorry for the confusion.
    I manage to change the array element by changing the row and column value. But, what i want is to allow the program to change the array element at a specified row and column value, where the new value is generated automatically by the program.
    Atatched is the diagram. I've detailed out the program . you may refer to the comments in the formula node. There are 2 arrays going into the loop. If a >3, then the program will switch to b, where if b =0, then the program will check on the value of the next element which is in the same row with b but in the next column. But if b =45, another set of checking will be done at a dufferent value of row and column.
    I hope that I have made the problem clear. Sorry if it is still confusing.
    Hope you can help me. Thank you!!!!
    Attachments:
    arrayrowncolumn2.JPG ‏64 KB

Maybe you are looking for

  • Simple question about JSF configuration

    I am using Tomcat 5.0 in Windows XP SP2. When I create a web application with JSF and put it into {tomcat_home}\webapps\, everything works perfect. But when I add a context path in Tomcat's server.xml such like <Context docBase="C:\works\java_project

  • Budgets in Investment Management

    I am looking to introduce Investment Management.  I am finding budgets very clunky, and far from user friendly, and I am wondering if there is a better way to deal with them.  can anybody advise on the following..... 1. I am currently inputting anual

  • Why is the reference library 2.2  api differences web page empty?

    I am trying to download the 2.2 API differences "first release" which is listed on the developer resources, and I get an empty page, am I the only one with this problem?

  • Change the address in Form 16

    Hi Friends Can anyone pls tell when we want to change the address in Form 16,where we will do that Regds lsp

  • IRecruitment Create Vacancy Approval Notifications

    Hi, I have a client that wishes me to modify the content of the Approval Notification/Message sent to the approver. Is this possible and how to you do it? In the User Guide it mentions using Application Developer and changing the messages but it is v