The main problem with array is that its size if fixed which only works when we know in advance how large our array will get. In most real world scenarios we don't really know in advance how large our array will get so we need a structure or mechanism through which we can create a list that automatically scales its size as we add elements.
There are 2 kinds of lists
Typically any List will need to provide the following methods as a basic functionality for it to be useable
We implemented a class that just does this called SimpleArrayList.java
package com.example.generics.arraylist;
import java.util.Arrays;
public class SimpleArrayList{
/* Simple implementation of Java's ArrayList
* Standard Java Methods
* get :: Get Element at an index
* put :: replace element at an index
* add :: add/append new element at the end of the list
* remove :: remove element at an index
* size :: get the size of the list
* */
public int[] elements; // array to hold elements
public int end; // track the next insertion point in the array
public SimpleArrayList(){
// [0,0,0,0]
elements = new int[5];
}
public int get(int index){
//get :: Get Element at an index
if(index>=end) return -1;
return elements[index];
}
public void put(int index, int value){
//put :: replace element at an index
if(index>=end) return; // throw exception
elements[index]=value;
}
public void add(int value){
// add :: add/append new element at the end of the list
if(end>=elements.length) scaleArray(); // if capacity exceeds then scale/double up the array
elements[end]=value;
++end; // increment end to point to next insertion point
}
public void remove(int index){
// remove :: remove element at an index
// if removal is after the end of the array then we don't have to do anything
if(end>=elements.length) return;
// remove the element and move the next elements back
for(int i=index;i+1<end;++i) elements[i]=elements[i+1];
--end; // move pointer back to replace the element as list size just shrank
}
void scaleArray(){
// Scale up the array when capacity if the array exceeds original capacity
int newElements[] = new int[elements.length*2]; // double the array
// write elements to new array
for(int i=0;i<elements.length;++i) newElements[i]=elements[i];
elements = newElements;
}
public int size(){
// size :: get the size of the list
return end;
}
@Override
public String toString(){
// Created to make printing possible
return Arrays.toString(elements);
}
}
Sorry ! I Don't remember, please raise it if you do
Sorry ! I Don't remember, please raise it if you do