Implement of Array

Posted by Ruizhi Ma on October 30, 2020
package test;

import java.util.Arrays;

public class MyArray {
	private int[] arr;

	// initialize
	public MyArray() {
		arr = new int[0];
	}

	//Add
	public void add(int nums) {
		// create an new array, longer 1 than the original
		int[] newArr = new int[arr.length + 1];
		// copy all elements to the new one
		for (int i = 0; i < arr.length; i++) {
			newArr[i] = arr[i];
		}

		// add the nums to the end of the new array
		newArr[newArr.length - 1] = nums;

		// copy the new array to the original one
		arr = newArr;
	}

	//Delete element according to index
	public void delete(int index) {
		//check the input
		if(index < 0 || index >= arr.length) System.out.println("Error: Out bound!");

		int[] newArr = new int[arr.length - 1];
		int j = 0;
		//copy all element before and after the index into the new arr
		for(int i = 0; i < arr.length; i++) {
			if(i == index) continue;

			newArr[j++] = arr[i];
		}

		//copy the new array to the original one
		arr = newArr;
	}

	//get func
	public void get(int index) {
		System.out.println(arr[index]);
	}

	//insert func
	public void insert(int index, int num) {
		//check
		if(index < 0 || index >= arr.length) System.out.println("Error: Out of bound error!");

		int[] newArray = new int[arr.length + 1];
		//copy element before and after the index into the new array
		int j = 0;
		for(int i = 0; i < newArray.length; i++) {
			if(i == index) continue;

			newArray[i] = arr[j++];
		}

		//insert the new element into the index
		newArray[index] = num;

		//copy the new array to the original one
		arr = newArray;

	}

	//Replace
	public void set(int index, int nums) {
		arr[index] = nums;
	}

	//Search
	public void search(int nums) {
		for(int i = 0; i < arr.length; i++) {
			if(arr[i] == nums) {
				System.out.println("the index of the element is " + i);
			}
		}
	}

	// show func
	public void show() {
		System.out.println(Arrays.toString(arr));
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyArray ma = new MyArray();
		// add elements at the end of array
		ma.add(99);
		ma.add(98);
		ma.add(97);
		ma.add(96);
		ma.add(95);
		ma.add(94);
		ma.add(93);
		ma.show();
		 //delete arr according to index
		 ma.delete(2);
		 ma.show();
		// get element according to index
		 ma.get(3);
		// index element to specified index
		 ma.insert(3, 0);
		 ma.show();
		// replace element according to index
		 ma.set(3, 10);
		 ma.show();
		 //Search element
		 ma.search(98);
	}

}