Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

java - How to convert linkedlist to array using `toArray()`?

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);
    }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...