Xvid Xvid - 1 month ago 6
Java Question

Returning contents from an Array

I try to assign an array of numbers from 1 to 10 using the code below. Basically I am stuck on how to return an array. Do I need a

toString
method ?

package arrays1;

import java.util.Arrays;


public class Arrays1 {

/**
* @param args the command line arguments
*/
private int[] numbers;
private int DEFAULT_SIZE = 10;


public Arrays1(int size){
numbers = new int[DEFAULT_SIZE];

}
public int[] add(int[] n)
{
for(int i=0; i<numbers.length; i++){

numbers[i]=n[i];}
return numbers;

}
public int[] getValues(){
return numbers;

}


public static void main(String[] args) {
// TODO code application logic here
Arrays1 A = new Arrays1(9);

System.out.println(A.getValues());
}



}


How do I return contents of an array from this code? Do I need to create a new object?

Answer

A.getValues() is returning a pointer to the integer array numbers object, which is probably the output you're seeing. You don't need a new object, just use the one you made, Arrays1 A, and iterate over its contents, so something like this:

public static void main(String[] args) {
        // TODO code application logic here
        Arrays1 A = new Arrays1(9);

        for (int i = 0; i < A.getValues().length; i++){
            System.out.println(A.numbers[i]);
        }
    }