Java using getters and setters for array [closed]

I would like to get this inventory_ array from another class.

public class File { 
Object[][] inventory=new Object[50][2];
//Reading file to the inventory array.

public class Stack { 
//I want to copy inventory array to here 

Lets assume I have 2 different classes and I have 2 different arrays.

public class inventory { 
Object[][] inventory_=new Object[50][2];

public class bag { 
Object[][] bag_=new Object[50][2];

So I want to compare inventory_’s items with bag_’s item in the bag class. How can I implement this.


Tehcnically it is possible to have a getter, that just returns the reference to the private Object[][] inventory array.

But this approach considered unsafe, because in this case, external code may change the internal state of your Fileclass via modifying the inventory array state.

For example:

class File {

    Object[][] inventory=new Object[50][2];

    public Object[][] getInventory() {
        return inventory;


For this case, let’s consider this example code:

class Stack {

    private File file;

    public Stack(File file) {
        this.file = file;

    void processSomething() {

        Object[][] stackInventory = file.getInventory();


And in case you assign something to stackInventory[1][1] (for example), then inventory[1][1] array element into File class instance also will change its value.

And thus it is not considered a good design approach, because it may lead to hard-to-catch bugs in your project.

There are two solutions for this case.

The first one: make defensive copy of the array in your getter.

public Object[][] getInventory() {
    Object[][] newInventory = new Object[50][2];

    // copy inventory array contents to the newInventory array

    return newInventory; // and returning safe copy of the array

In this case as you have Object, it is still possible to change internal state of the objects if they are mutable ones.

Either make your objects immutable, or employ deep copy approach upon making defensive copy of the array.

And another way to resolve this issue, which I recommend, is using the Iterator approach.

In your File class make a method that returns the Iterator over your inventory array. And use this iterator in the external code to iterate over the inventory elements.

Or you may make your File class iterable and use foreach operator to process the inventory elements.

Once again, upon designing your approach, keep in mind the mutable/immutable class types. And if it is possible, keep your classes immutable.

Also it is not recommended to name your classes likewise the standard java sdk classes. Your File class could be confused with class by someone who will read your code later.

The same goes for your Stack class, which can be confused with java.util.Stack class. Please use other, more descriptive and unique names.

Leave a Reply

Your email address will not be published. Required fields are marked *