The DynamicArrayOfInt class is a simple implementation of a dynamic array in Java. A dynamic array is a resizable array that can grow or shrink in size as needed. This class provides methods to manipulate and interact with this dynamic array of integers. In the constructor, initially the data array has a size of 1 and grows as necessary.

The method put(); is used to store the value at the specified position in the array. There is no pre-set limit on how large position can be, although for very large values there would be problems with having enough computer memory. The function get(); is used to retrieve the value stored in the specified position. If no value has ever been put at that position, then the value is zero.

Java Dynamic Array Example

Example Usage of Dynamic Array

Class Members:

private int[] data: This is an array that holds the integer values. The size of this array increases dynamically when needed.


DynamicArrayOfInt(): This is the constructor of the class. It initializes the dynamic array with a default size of 1. As elements are added, the array will automatically resize to accommodate more elements.


get(int position): int

  • Description: Retrieves the value at the specified position in the dynamic array.
  • Parameters: position: The index from which the value is to be retrieved.
  • Return Value: The integer value at the specified position. If the position is outside the current array bounds, 0 is returned.

put(int position, int value): void

  • Description: Stores a value at the specified position in the dynamic array. If the position is beyond the current array size, the array is resized to include the specified position.
  • Parameters: 
  • position: The index at which the value is to be stored.
  • value: The integer value to be stored.

remove(int position): void

  • Description: Removes the element at the specified position in the dynamic array. The array is then resized to eliminate the gap.
  • Parameters: position: The index of the element to be removed.

size(): int

  • Description: Returns the current number of elements in the dynamic array.
  • Return Value: The number of elements in the array.

clear(): void

  • Description: Clears all elements from the array and sets its size back to 1.

contains(int value): boolean

  • Description: Checks if the specified value exists in the dynamic array.
  • Parameters: value: The value to be checked.
  • Return Value: true if the value is found, false otherwise.

print(): void

  • Description: Prints the elements of the dynamic array for debugging or testing purposes.

How to use the Dynamic Array?

  • Use the put method to add elements to the dynamic array.
  • Check the size of the array using the size method.
  • Remove elements using the remove method when necessary.
  • Clear the array using the clear method if you want to start fresh.
  • Use the contains method to check if a specific value is present in the array.