Java HashSet 到数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20275789/
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 00:46:43  来源:igfitidea点击:

Java HashSet to array

javaarrayssethashset

提问by PenguinProgrammer

I'm trying to convert a HashSet to an Array of Doubles. Yes I have a main method and class defined, I've just included what I've imported as well as the code for this specific function.

我正在尝试将 HashSet 转换为双精度数组。是的,我定义了一个主要的方法和类,我刚刚包含了我导入的内容以及这个特定函数的代码。

This is the Error that shows up:

这是显示的错误:

Ass10.java:148: error: no suitable method found for toArray(double[])
                rtrn = s.toArray(rtrn);

Here is the code:

这是代码:

import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;


public static double[] negated(double[] a) {
        Set<Double> s = new HashSet<Double>();
        for(double x : a) {
            s.add(x);
        } for(double x : s) {
            if(s.contains(-x) == false) {
                s.remove(x);
            }
        }
        double[] rtrn = new double[s.size()];
        rtrn = s.toArray(rtrn);
        return rtrn;
        }

采纳答案by Costi Ciudatu

You can't use a primitive array in this scenario, as there's no auto-boxing for arrays in Java. Use a Double[]for that to work.

在这种情况下不能使用原始数组,因为 Java 中没有数组的自动装箱。使用 aDouble[]来工作。

回答by peter.petrov

This is a compile time error, right? Try using Double[] instead of double[].

这是一个编译时错误,对吧?尝试使用 Double[] 而不是 double[]。

回答by Sage

Java collections works with reference type. The function Collection.toArray(T[] a)has a signature of generic reference type. So you will need to pass a reference type array instead of primitive array. The corresponding reference type of primitive type doubleis Double.

Java 集合使用引用类型。该函数Collection.toArray(T[] a)具有通用引用类型的签名。所以你需要传递一个引用类型数组而不是原始数组。原始类型对应的引用类型doubleDouble.

Double[] rtrn = new Double[s.size()];
rtrn = s.toArray(rtrn);