1

So I'm to write a simple thing which reads an input file till EOF reached - the file consists of int-double pairs. I'm to calculate the average of all the elements in the second array and finally have both sets of data stored in respective arrays of primitive data types.

Of course the task is easy so the question isn't directly about it - rather, about the array part. As I don't know how many pairs I'll have to store, I use two ArrayLists to store it. The spec strictly points that in the end, however, both ints and doubles have to be store in primitive arrays - and here comes my question. Is there some faster way to do this than just copying the ArrayList to a primitive type array? I can't use an array from the beginning since I don't know the size or even an upper bound and using toArray() also woulnd't work as I have to have primitive int[] and double[] in the end, not objects of Integer[] and Double[].

Noel M
  • 15,812
  • 8
  • 39
  • 47
Straightfw
  • 2,143
  • 5
  • 26
  • 39
  • Possible duplicate of http://stackoverflow.com/questions/1109988/how-do-i-convert-double-to-double – jbowes Nov 10 '12 at 11:50

2 Answers2

2

You should be able to cast from a Double to a primitive double.

Something like:

    ArrayList<Double> test = new ArrayList<Double>();
    //Get your values into the ArrayList here.

    double[] values = new double[test.size()];
    for(int i = 0; i < test.size(); i++){
        values[i] = test.get(i).doubleValue();
    }

As far as I know, there isn't more a "nice" way of doing it than just copying it straight across...

nitsua
  • 763
  • 8
  • 20
1

No there is no direct easy way to do it. Converting an ArrayList to a plain array is not that bad as the ArrayList can grow automatically while you should take care for allocating a new array if you have more elements than the one you expected. In the end nothing will change sinche the ArrayList exactly does the same thing but without the need to worry about it.

As for primitive types vs types there is no problem in Java, you can unbox and box them almost for free.

By the way the class ArrayUtil of apache-commons has the method toPrimitive which does this for you.

Jack
  • 131,802
  • 30
  • 241
  • 343