Java data structure (1) -- array



       ①, how to insert a new data item

  ②, how to find a specific data item

  ③ How to delete a specific data item

  4. How to iteratively access each data item for display or other operations

  And we know the simple usage of array, now we encapsulate an array with the idea of ​​class to realize the above four basic functions:

  ps: Assuming that the operator will not add duplicate elements, duplicate elements are not considered here. If duplicate elements are added, subsequent operations such as searching, deleting, and modifying will only be valid for the element that appears for the first time.

 
 
package Array;

public class MyArray {
	//define an array
	private int [] intArray;
	//Define the actual length of the array
	private int elems;
	//Define the maximum length of the array
	private int length;
	
	//Construct an array of length 100 by default
	public MyArray(){
		elems = 0;
		length = 100;
		intArray = new int[length];
	}
	//Constructor, initialize an array of length length
	public MyArray(int length){
		elems = 0;
		this.length = length;
		intArray = new int[length];
	}
	
	//Get the effective length of the array
	public int getSize(){
		return elems;
	}
	
	// loop through the display elements
	public void display(){
		for(int i = 0; i < elems; i++){
			System.out.print(intArray[i]);
		}
		System.out.println();
	}
	
	//add element
	public boolean add(int value){
		if(elems == length){
			return false;
		}else{
			intArray[elems] = value;
			elems++;
		}
		return true;
	}
	
	// get element by subscript
	public int get(int i){
		if(i<0 || i>elems-1){
			System.out.println("Access subscript out of bounds");
			return -1;
		}
		else{
			return intArray[i];
		}
	}
	
	//find element
	public int find(int searchValue){
		int i;
		for(i = 0; i < elems; i++){
			if(intArray[i] == searchValue){
				break;
			}
		}
		if(i == elems){
			return -1;
		}
		return i;
	}
	
	// delete element
	public boolean delete(int value){
		int k = find(value);
		if(-1 == k){
			System.out.println("The number to be deleted does not exist");
		}else{
			if(k == elems-1){
				elems--;
			}else{
				for(int i = k; i<elems-1; i++){
					intArray[i] = intArray[i+1];
				}
				elems--;
			}
		}
		return true;
	}
	
	//change the data
	public boolean modify(int oldValue,int newValue){
		int k = find(oldValue);
		if(-1 == k){
			System.out.println("The number to be modified does not exist");
			return false;
		}else{
			intArray[k] = newValue;
		}
		return true;
	}
}


 
 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324768950&siteId=291194637