13

I do not know how to convert a linked list of doubles to array. Please help me find the error.

import java.util.*;
public class StackCalculator {


  private   LinkedList<Double> values;
  double value1 , value2 ;

  public StackCalculator()
  {
     values = new LinkedList<Double>();
  }


    void push(double x)
    {
         values.addFirst(x);
    }
    double pop()
    {
       return values.removeFirst();
    }
    double add()
    {
        value1=pop();
        value2=pop();
        return (value1 + value2);
    }

    double mult()
    {
        value1=pop();
        value2=pop();
        return (value1 * value2);
    }


    double[] v = new double[10];
    double[] getValues()
    {
        return   values.toArray(v);
    }

}
0

3 Answers 3

28

The List#toArray() of a List<Double> returns Double[]. The Double[] isn't the same as double[]. As arrays are objects, not primitives, the autoboxing rules doesn't and can't apply here.

Either use Double[] instead:

Double[] array = list.toArray(new Double[list.size()]);

...or create double[] yourself using a simple for loop:

double[] array = new double[list.size()];
for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i); // Watch out for NullPointerExceptions!
}
Sign up to request clarification or add additional context in comments.

3 Comments

ow, O(n^2) for loop? why not int i = 0; for (Double v : list) array[i++] = v;
Yeah that second option is pretty terrible. Sparkleshy's suggestion would be much better.
Using a foreach will do much better, as it will use an Iterator if possible.
4

The problem is the type of your list, which is Double (object), while you're trying to return an array of type double (primitive type). Your code should compile if you change getValues() to return a Double[].

For your other methods, it's not a problem, because Java automatically converts Doubles to doubles and back (called autoboxing). It cannot do that for array types.

Comments

1

toArray is defined to return T[] where T is a generic argument (the one-argument version is anyway). Since primitives can't be used as generic arguments, toArray can't return double[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.