dan_jen1
dan_jen1

Reputation: 1

Set and Get an array of Doubles

I'm very new to Java and confused about getting an setting arrays. Just super basic code I want to update the array of grades in the Student Class. I setGrades with the double[] input array, but when I call getGrades it returns junk: [D@610455d6.

I know it's something super easy I'm missing

public class Student
{
    private double[] grades;

    public void setGrades(double[] grades)
    {
        this.grades = grades;
    }

    public double[] getGrades()
    {
        return grades;
    }

    public static void main(String[] args)
    {
        double[] input = {87.54, 67.45};
        Student ted = new Student();
        ted.setGrades(input);
        System.out.println(ted.getGrades());
    }
}

Upvotes: 0

Views: 298

Answers (4)

EthanBar
EthanBar

Reputation: 705

Printing an array in Java returns its hash code, which is what [D@610455d6 is. You'll either need to specify an index in getGrades() or use Arrays.toString(ted.getGrades()) to turn the array into a printable format.

Upvotes: 0

synchronizer
synchronizer

Reputation: 2075

Objects in Java override a function called toString(), which returns whatever String representation of the object is defined in the class, and toString() is called implicitly when you pass an instance of an object to the print method. A primitive Array does not return a very useful String representation--just the hashCode used when hashing the object for placement in (for example) a HashMap. The Arrays utility class, however, includes a more useful toString() function that you must call explicitly, passing the array as an argument.

Arrays.toString(ted.getGrades());

I suggest figuring how to access individual elements of the grades array without returning it though. It's commonly a bad idea to leave a way to access internal object data without control. You could decide to clobber the internal array somewhere else in your program if you save a reference to it. One possibility is to pass the grades array to your object constructor and have that constructor do a full copy of that array. Then, have a getter and setter for individual array index accesses instead of access to the entire array.

Upvotes: 0

Emanuel
Emanuel

Reputation: 8106

Because you return an array.

getGrades()[0] 

gets the first element in your Array

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59996

To print the values of your array you have to loop throw your array and print value by value, but there are a better way so instead of :

System.out.println(ted.getGrades());

you have to use Arrays.toString(array) like this :

System.out.println(Arrays.toString(ted.getGrades()));

Upvotes: 3

Related Questions