Array List: Insertion and Deletion Mechanism
Code:
/*
* This is a simple program that enable dynamic deletion and.
* insertion of data element from and into an array object.
*/
package arraydatastructure;
import java.util.Arrays;
/**
*
* @author Adeniran Adetunji
*/
public class Insert_Delete_from_Array {
//This method delete element at position 'pos' from and array 'data'
public int [] deleteElement (int[]data, int pos)
{
//check if postion 'pos' is within the length of the array
if(pos >= 0 && pos <data.length)
{
int[] dataCopy = new int[data.length-1];
System.arraycopy (data, 0, dataCopy, 0, (pos-1));
System.arraycopy(data, pos,dataCopy, pos-1,
dataCopy.length-(pos-1));
dataCopy.length-(pos-1));
data=dataCopy;
}
return data;
}
//Method to insert data element into an array
public int [] InsertElement (int[]dataA,int data, int pos)
{
if(pos >= 0 && pos <dataA.length)
{
int[]dataCopy= new int[dataA.length+1];
//adding element to array
System.arraycopy(dataA, 0, dataCopy, 0, pos-1);
dataCopy[pos-1] = data;
System.arraycopy(dataA, pos-1, dataCopy, pos,
dataA.length-(pos-1));
dataA.length-(pos-1));
dataA = dataCopy;
}
return dataA;
}
// Testing the methods in the 'main' method
public static void main(String args[]) {
//creating array 'a' with data 1,2,3,4,5,6,7,8,9,10
int[]a = {1,2,3,4,5,6,7,8,9,10};
//converting array 'a' to string and print
System.out.println(Arrays.toString(a));
//creating and object of the type Insert_Delete_from_Array
Insert_Delete_from_Array obj = new Insert_Delete_from_Array();
//delet element at postion 7 from array a
a = obj.deleteElement(a, 7);
//Convert array 'a' to string and print
System.out.println(Arrays.toString(a));
//insert '21' into postiont '8' in array 'a'
a = obj.InsertElement(a, 21, 8);
System.out.println(Arrays.toString(a));
}
}
Output:
run:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 8, 21, 9, 10]
BUILD SUCCESSFUL (total time: 9 seconds)
No comments:
Post a Comment
Please drop your comment here, thanks.