2

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.

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;
        }
1
  • Essentially there is no way to case a double[] to a Double[] like there is a double to a Double and visa versa. Commented Nov 28, 2013 at 22:47

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 double is Double.

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

Comments

0

This is a compile time error, right? Try using Double[] instead of 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.