Reputation: 9
I have been trying to create my own Array
class, which is dynamic, but I can't figure out the problem
in resizing the size of it. I created separate function to check if the array is full and for resizing it. But I think it is unable to call either one of those.
public class Array {
private int[] array;
private int size;
public int pointer;
private static int DEFAULT_SIZE = 5;
Array() {
this(DEFAULT_SIZE);
}
Array(int size) {
this.size = size;
this.array = new int[size];
}
public void add(int element) {
if (isFull()) {
resize();
}
array[pointer] = element;
pointer++;
}
private boolean isFull() {
return pointer == array.length;
}
private void resize() {
int[] temp = new int[size * 2];
for (int i = 0; i < array.length; i++) {
temp[i] = array[i];
}
array = temp;
}
public void print() {
for (int i = 0; i < size; i++) {
System.out.println(array[i]);
}
}
}
Upvotes: 0
Views: 662
Reputation: 265211
You are never updating the size
after allocating the bigger array:
private void resize() {
int[] temp = new int[size * 2];
for (int i = 0; i < array.length; i++) {
temp[i] = array[i];
}
array = temp;
}
This will leave size
at the initial value of 5
. You have to add size *= 2
at the end of your method (or at the start and then only do new int[size]
).
Please note that the size
field is totally redundant, because it is already tracked and accessible via array.length
(which you are already using in your loop's condition).
print
seems to be incorrect, as it always prints the full array, even the items which have not been added yet. You likely want to user pointer
instead of size
(otherwise, you are going to print lots of zeros):
public void print() {
for (int i = 0; i < pointer; i++) {
System.out.println(array[i]);
}
}
Upvotes: 2