Java dynamic array sizes?
In Java, you can implement a dynamic array (i.e., an array that can grow and shrink as needed) by using an ArrayList or an ArrayDeque
. These classes are part of the Java Collection Framework and provide resizable-array and double-ended queue implementations, respectively.
Here's an example of how you can use an ArrayList to implement a dynamic array:
import java.util.ArrayList;
public class DynamicArray {
private ArrayList<Integer> numbers;
public DynamicArray() {
numbers = new ArrayList<>();
}
public void add(int num) {
numbers.add(num);
}
public int get(int index) {
return numbers.get(index);
}
public int size() {
return numbers.size();
}
}
Here's an example of how you can use an ArrayDeque
to implement a dynamic array:
import java.util.ArrayDeque;
public class DynamicArray {
private ArrayDeque<Integer> numbers;
public DynamicArray() {
numbers = new ArrayDeque<>();
}
public void add(int num) {
numbers.add(num);
}
public int get(int index) {
return numbers.get(index);
}
public int size() {
return numbers.size();
}
}
If you prefer to implement a dynamic array using a raw array, you can do so by creating a new array and copying all the elements whenever the array is full. Here's an example of how you can do this:
public class DynamicArray {
private int[] numbers;
private int size;
public DynamicArray() {
numbers = new int[10];
size = 0;
}
public void add(int num) {
if (size == numbers.length) {
int[] temp = new int[numbers.length * 2];
System.arraycopy(numbers, 0, temp, 0, numbers.length);
numbers = temp;
}
n