Array Implementation
The Array class in Java consists of the following methods:
- insert(int value, int idx): Insertion of an element at any position of array.
- append(int value): Appending an element at the end of array.
- delete(int idx): Deleting an element from any position in an array.
- remove(): Removing an element from the end of an array.
- show(): Displaying the array.
The data members of Array class consists:
- len: Tells the length of array.
- size: Private member stores the maximum length of array.
- arr[]: Private array of the class.
class Array {
int len;
private int size;
private int arr[];
Array(int size) {
len = 0;
this.size = size + 10;
arr = new int[this.size];
}
boolean insert(int value, int idx) {
if (idx > len || len == size || idx < 0)
return false;
for (int i = len - 1; i > idx - 1; i--)
arr[i + 1] = arr[i];
arr[idx] = value;
len++;
return true;
}
boolean append(int value) {
if (len == size)
return false;
arr[len] = value;
len++;
return true;
}
boolean delete(int idx) {
if (idx > len - 1 || idx < 0)
return false;
for (int i = idx; i < len - 1; i++)
arr[i] = arr[i + 1];
len--;
return true;
}
boolean remove() {
if (len == 0)
return false;
arr[len - 1] = 0;
len--;
return true;
}
void show() {
for (int i = 0; i < len; i++)
System.out.print(arr[i] + " ");
}
}
Comments
Post a Comment