Array Data Structure Java Example
The following example shows how to abstract array data structure functionality and make it easier to design a program. The user life is made easier and the user doesn’t even need to know what kind of data structure the ArrayDataStructure class is using to store the data.
Array data structure with high-level methods
package com.sneppets.dsalgo; public class ArrayDataStructure { //reference to array arr private long[] arr; //number of elements in the array private int n; //constructor public ArrayDataStructure (int arrSize){ //create array arr = new long[arrSize]; //no elements yet n = 0; } //find element public boolean find (long elementKey){ int i; for (i=0; i<n; i++){ if (arr[i] == elementKey) break; } if (i == n){ return false; } else{ return true; } } //insert element into array public void insert(long element){ //insert element arr[n] = element; //increment size n++; } public boolean delete(long element){ int i; for (i=0; i<n; i++){ if(element == arr[i]) break; } if (i == n){ return false; } else { //move higher ones down for(int j=i; j<n; j++){ arr[j] = arr[j+1]; } //decrement size n--; return true; } } //display array contents public void display(){ for(int i=0; i<n; i++){ System.out.println(arr[i]+ " "); } } }
ArrayDataStructureTest.java
package com.sneppets.dsalgo; public class ArrayDataStructureTest { public static void main (String[] args){ //array size int arrSize = 10; //reference to array data structure ArrayDataStructure arrayDS; //create the array arrayDS = new ArrayDataStructure(arrSize); //insert 5 elements arrayDS.insert(11); arrayDS.insert(33); arrayDS.insert(55); arrayDS.insert(22); arrayDS.insert(44); //display array elements arrayDS.display(); //search for element 77 int element = 77; if(arrayDS.find(element)){ System.out.println("Found element "+ element); } else{ System.out.println("Could not find element "+ element); } //delete 2 elements arrayDS.delete(33); arrayDS.delete(55); //display again arrayDS.display(); } }
Output:
11 33 55 22 44 Could not find element 77 11 22 44