1

String numbers = ("5,25,77,44,64,8,55,28,86,35");

I would like to return an array of double values from the string. I am unable to do that successfully with the following code :

public static double[] fillArray(String numbers)
{
    String[] answers = numbers.split(",");

    double[] boom = new double[answers.length];

    for (int index = 0; index < answers.length; index++)
    {
        boom[index] = Double.parseDouble(answers[index]);
    }

    return boom;
}

The error I get is quite weird...

 [De56f047c 

Why is that and how do I fix it?

Amit Verma
  • 40,709
  • 21
  • 93
  • 115
  • 1
    You can check [here](http://stackoverflow.com/questions/409784/simplest-way-to-print-an-array-in-java) to see how to simply print out an array. – Obicere Mar 14 '14 at 20:45

3 Answers3

8

You're calling toString() on an array - and arrays don't override Object.toString(). So you get the behaviour from Object.toString():

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Call Arrays.toString(double[]) on the result instead and it will be fine. So this code:

double[] array = fillArray("5,25,77,44,64,8,55,28,86,35");
System.out.println(Arrays.toString(array));

... gives a result of:

[5.0, 25.0, 77.0, 44.0, 64.0, 8.0, 55.0, 28.0, 86.0, 35.0]

I really wish toString() had been overridden for all arrays. It would make life simpler...

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

If I follow what you want, you can use this -

public static void main(String[] args) {
    String numbers = ("5,25,77,44,64,8,55,28,86,35");
    List<Double> al = new ArrayList<Double>();
    for (String str : numbers.split(",")) {
        al.add(Double.valueOf(str));
    }
    double[] boom = new double[al.size()];
    for (int i = 0; i < al.size(); i++) {
        boom[i] = al.get(i);
    }
    System.out.println(Arrays.toString(boom));
}

Output is,

[5.0, 25.0, 77.0, 44.0, 64.0, 8.0, 55.0, 28.0, 86.0, 35.0]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You're not printing out the array result properly.

double[] array = fillArray("5,25,77,44,64,8,55,28,86,35");

You probably did this:

System.out.println(array);

But you can't do that to print out an array.

The result you got is the

name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object.

Look here to read up on that.

You need to iterate through the array, or use Arrays.toString(array[])

So for example:

for (double d : array) { 
    System.out.print(d + " ");
}

Or simply:

System.out.println(Arrays.toString(array));
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97