'How do I make several objects refer to one common array?

Program creates several Example objects that each must add their own number into one array. The problem is that each object refers to its own array, not the common one. How do I make objects refer to one common array?

My code:

class Example {
    private int[] array = new int[5];
    private int number;

    public Example(int number) {
        this.number = number;
    }

    public void addInArr(int x) {
        for(int i=0; i<array.length; i++) {
            if(array[i]==0) {
                array[i] = x;
            }
            break;
        }
    }

    public void showArr() {
        for(int i=0; i<array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }

    public static void main(String[] args) {
        for(int i=1; i<6; i++) {
            Example obj = new Example(i);
            obj.addInArr(i);
            obj.showArr();
        }
    }
}

The code outputs: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 5 0 0 0 0

The code must output: 1 2 3 4 5



Solution 1:[1]

Perhaps the simplest is to define the array as a static member of the class.

public class StaticExample {
  private static int[] array = new int[5];
  ...
  public int getLength() {
    return array.length;
  }
}

Solution 2:[2]

Your main thread is working in the same array. Your problem has nothing about multithreading. Your addInArray() method logic is not correct. You have 5 spots in your array but you always adds the new value at position 0. So the others spots are 0 as the default value for int.

You likely need a new variable to store the current position of your array starting as 0.

private int position = 0;

public void addInArr(int x) {
   array[position] = x;
   position++;
}

Attention: If you add more than five numbers it will generate an error because your array has only 5 slots.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vsfDawg
Solution 2 Luis Felipe Martins