Author, read about the singleton design pattern , maybe you need him? For the given formulation of the problem sounds very strange (and in general it is not clear why this is all needed).
But I still try to translate into reality the task of the author ( again, if I understood her correctly ) with a simple example.
Data class:
public class Data { private static int[] mArray; private static int mSize; public Data(int capacity) { if (mArray == null) { mArray = new int[capacity]; mSize = 0; } else { // some actions } } public void add(int value) { if (mSize < mArray.length) { mArray[mSize] = value; mSize++; } else { // some actions } } public void print() { for (int i=0; i<mSize; i++) { System.out.print(mArray[i] + " "); } System.out.println(); } }
Example of use:
Data dateOne = new Data(7); dateOne.add(1); dateOne.add(2); dateOne.add(3); Data dateTwo = new Data(15); dateTwo.add(4); dateTwo.add(5); dateTwo.add(10); System.out.print("dateOne: "); dateOne.print(); System.out.print("dateTwo: "); dateTwo.print();
Output to console:
dateOne: 1 2 3 4 5 10 dateTwo: 1 2 3 4 5 10
The fields mArray and mSize declared as static , this achieves the necessary:
I need that when I create 2 instances of this class, their elements are written to one array
In this implementation, the capacity of the array is set using the constructor when creating the first instance (the constructor calls will be ignored during all subsequent creation of objects of this class).
UPD . Regarding the extension:
public Data(int capacity) { if (mArray == null) { mArray = new int[capacity]; mSize = 0; } else { mArray = Arrays.copyOf(mArray, mArray.length + capacity); } }
In this case, the second and subsequent calls to the constructor will expand the capacity of the array by capacity .
(s + 1)-th element to it or to retrieve an element that has not been previously added? - m. vokhm