Java – Getters, Setters, Arrays

arraysgetterjavasetter

I am unsure if this is possible or not. I've done my research and didn't find much at all. This proves very difficult for me and I'm just hoping there is a way.

Question: Is it possible to send the WHOLE array(that is all the values that the array contains) using getters and setters to another class?

So me Example and problem:

Let's say in one class I have:

public class(){
private String[] array= new String[300]

public String[] getArray()
{
return array;
}

public void setArray(String[] array)
{
this.array = array;
}
}

Now lets just say the array is filled with values.
I then want to get these values in another class.

public void class2(){
public static void main(String[] args){
        String[] array= new String[300];
        class c = new class();
        array[]=c.getArray(); //I know this is wrong I am just unsure what syntax or methods to use

I hope I explained my question properly.

EDIT: okay now that the file can compile when I do use

array=c.getArray();

and output the array using a for loop it displays null for everything. Can someone please explain why?

Best Solution

The only potential issue, in the trivial implementation

A[] getArray() { return myArray; };

the getter will normally return the reference to the array. The calling code will be able to retain this reference observing the (potentially changed) content, and modify it, potentially causing strange behavior of unrelated parts of code that call the getter again. This is especially important when some library runs linked with untrusted code; in such case security flaws may be possible.

To avoid, it is better to return the copy of the set array using the arrays clone() method:

   A[] getArray() { return myArray.clone(); }
   void setArray(A array) { myArray = array.clone(); }

Of course, this decreases performance in case the array is really large. Cloning may not be as important in some program you fully control and can use code review instead to exclude inappropriate modifications of the array.