COMP2247 - Algorithms and Data Structures

Syllabus Software Installation Assignments Tests
Lectures and Labs
**Back to Full Menu**

ArrayList ArrayListProcessing.java NameSearching.java Hardware Store Program With ArrayList MyArrayList Program
MyArrayList.java
MyArrayListClient.java




MyArrayList Program


Description

The program defines the class MyArrayList to implement the functionalities of ArrayList such as get, add, remove, and set methods.

This client program creates an object of MyArrayList and then tests the methods such as get, add, remove, set, and toString.

Define MyArrayList class

Create an object of MyArrayList

Add objects to the list with hard-coded values

Call add, get, remove, set, and toString methods

Associated Concepts:

ArrayList

Algorithm:

MyArrayList class:

Constructor:

Create a generic array with initial capacity of 10: myArray

Initialize the size to 0

size() method:

return the size

checkIndex(index, size) method:

Throw an exception if the index is out of bound.

get(index) method:

Validate the index

Return the object at a given index if the index if valid.

add(object) method:

Expand the array if the array is full.

Add the object as the last object in the array.

Increment the size

add(index, object) method:

Validate the index

Expand the array if the array is full.

Shift objects to make room for adding the object at the given index.

Add the object at the given index.

Increment the size

remove(index) method:

Validate the index

Use a variable to hold the object to be removed at the given index.

Shift objects to fill the gap

Decrement the size

Return the removed object

set(index, new object) method:

Validate the index

Use a variable to hold the object to be replaced at the given index.

Assign the new object to the given index

Return the replaced the object

Client program:

Create a MyArrayList of String and use the object reference to call the methods:

Call add method to add objects

Call toString method to print the list

Call get method to get the object at index 1

Call set method to replace the object at index 0 with a new object

Call remove method to remove the object at index 1

Call toString method to print the list