You should add an attribute in the Node
class to know the current index you are for the current Node's array. I would also add an attribute in your DynamicArrayOfInts
to keep a reference for the current node.
Then in your add method, check if the array that the current node have is not full (it can be done easily because you know the value of the index and the number of elements per node).
If it's not the case (or if the head is null for the first add call), create a new node and add the element in its array, otherwise just fill the next slot of the array for the current node.
This is how I would implement it.
class DynamicArrayOfInts {
private Node head, current;
private int numOfElementsPerNode;
public DynamicArrayOfInts(int elementsPerNode) {
if(elementsPerNode <= 0)
throw new IllegalArgumentException("elementsPerNode must be > 0");
numOfElementsPerNode = elementsPerNode;
}
public void add(int e) {
if(head == null){
head = new Node(numOfElementsPerNode, null);
head.data[head.index++] = e;
current = head;
return;
}
if(current.index == numOfElementsPerNode){
Node n = new Node(numOfElementsPerNode, null);
current.next = n;
current = n;
}
current.data[current.index++] = e;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder();
Node n = head;
while(n != null){
sb.append(Arrays.toString(n.data));
n = n.next;
}
return sb.toString();
}
private static class Node {
private int[] data;
private int index;
private Node next;
public Node(int n, Node nxt) {
data = new int[n];
index = 0;
next = nxt;
}
}
}
A small main to show how it behaves:
public static void main(String[] args){
int[] toAdd = {5,7,10,-1};
DynamicArrayOfInts d = new DynamicArrayOfInts(2);
for(int i : toAdd){
d.add(i);
System.out.println(d);
}
}
Output:
[5, 0]
[5, 7]
[5, 7][10, 0]
[5, 7][10, -1]