Write a class ArrayList that represents an array of integers
Solution
Hi, Please find my ArrayList implementation.
Please let me know in case of any issue:
############# ArrayList.java ##################
public class ArrayList {
private int[] array; // array to store element
private int size; // to maintain current size of array
private int capacity; // to store the capacity of array
public ArrayList(){
// initializing capacity with 1
capacity = 1;
// creating an array of size 1
array = new int[capacity];
// initializing size with zero
size = 0;
}
// function to resize current size with double the current capacity and storing old values
private void resize(){
// creating an array of double of current capacity
int newArr[] = new int[2*capacity];
capacity = 2*capacity; // increasing capacity value
// storing old values in new array
for(int i=0; i<size; i++){
newArr[i] = array[i];
}
// pointing array to new array
array = newArr;
}
public void add(int x){
if(size == capacity){ // if array is full, then resize
resize();
}
// adding new element
array[size] = x;
// increasing size
size = size + 1;
}
public int get(int index){
// if index of out of bound
if(index >= size){
throw new ArrayIndexOutOfBoundsException(index+ \" is put of bound\");
}
return array[index];
}
// function to display
public void display(){
if(size == 0){
System.out.println(\"Array is Empty\");
return;
}
for(int i=0; i<size; i++){
System.out.print(array[i]+ \" \");
}
System.out.println();
}
public int getSize(){
return size;
}
}
############## ArrayListTest.java ################
public class ArrayListTest {
// function to check whether x is prime or not
public static boolean isPrime(int x){
if(x < 2)
return false;
for(int i=2; i<=x/2; i++){
if(x%i == 0)
return false;
}
return true;
}
public static void main(String[] args) {
// creating object of ArrayList class
ArrayList list = new ArrayList();
// adding all prime number in range 1-50
for(int i=1; i<=50; i++){
if(isPrime(i))
list.add(i);
}
// displaying arraylist content
for(int i=0; i<list.getSize(); i++){
System.out.print(list.get(i)+\" \");
}
System.out.println();
// or you can call display method
System.out.println(\"Calling display method\");
list.display();
}
}
/*
Sample run:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
Calling display method
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
*/



