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

前端 未结 3 1716
不知归路
不知归路 2020-12-17 16:36

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         


        
相关标签:
3条回答
  • 2020-12-17 16:45

    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!
    }
    
    0 讨论(0)
  • 2020-12-17 16:53

    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[].

    0 讨论(0)
  • 2020-12-17 17:08

    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.

    0 讨论(0)
提交回复
热议问题