Java 如何使用`toArray()`将链表转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2304242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:54:03  来源:igfitidea点击:

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

java

提问by kathy

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

}

回答by Jorn

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

问题在于您的列表的类型,即Double(对象),而您试图返回一个类型double(原始类型)的数组。如果您更改getValues()为返回一个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.

对于您的其他方法,这不是问题,因为 Java 会自动将Doubles转换为doubles 并返回(称为自动装箱)。对于数组类型,它不能这样做。

回答by sepp2k

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

toArray被定义为返回T[]其中 T 是泛型参数(无论如何都是单参数版本)。由于基元不能用作通用参数,因此 toArray 不能返回double[]

回答by BalusC

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

List#toArray()一个的List<Double>回报Double[]。与Double[]不一样double[]。由于数组是对象,而不是基元,因此自动装箱规则不适用于也不能在这里应用。

Either use Double[]instead:

要么Double[]改用:

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

...or create double[]yourself using a simple forloop:

...或double[]使用一个简单的for循环创建自己:

double[] array = new double[list.size()];
for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i); // Watch out for NullPointerExceptions!
}