Question: 1 . Array Exercise: Implement a Java class DynamicArray that mimics the functionality of an ArrayList. Include methods for adding, removing, and accessing elements. Demonstrate

1. Array Exercise:
Implement a Java class DynamicArray that mimics the functionality of an ArrayList.
Include methods for adding, removing, and accessing elements. Demonstrate method
overloading by implementing multiple versions of the add and remove methods (e.g.,
adding at a specific index vs. adding at the end).
Initialization: Start by defining a private array to store the elements and an integer
to keep track of the current size. Consider starting with a default capacity and
expanding it as needed.
Adding Elements: When adding an element, check if the array needs to be
resized. To resize, create a new larger array, copy the existing elements into it,
and then add the new element.
Removing Elements: When removing an element, shift all subsequent elements
one position to the left to fill the gap. Consider shrinking the array size if too
much space is unused.
Accessing Elements: Implement a method to access elements by their index.
Include error checking to prevent accessing out of bounds.
Method Overloading: For adding, implement two methods: one that adds to the
end and another that inserts at a specific index. For removing, similarly,
implement methods for removing by index and another by value (optional
challenge).
1. Array Exercise: DynamicArray Class
public class DynamicArray {
private int[] array;
private int size;
private int capacity;
public DynamicArray(){
capacity =10;
array = new int[capacity];
size =0;
}
// YOUR CODE HERE
// Method for demonstration purposes
public static void main(String[] args){
DynamicArray da = new DynamicArray();
da.add(5);
da.add(6);
da.add(1,7); // Demonstrating method overloading
System.out.println("Element at index 1: "+ da.get(1));
da.remove(1);
System.out.println("Size after removing an element: "+
da.size());
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!