1. 程式人生 > >一 自定義數組類

一 自定義數組類

構造 增刪 del 個數 刪除數據 new err ray 重載

用類封裝一個數組以及對數組的增刪改查的操作。

源代碼:

public class Myarray {
private int[] array; //創建數組
private int element; //有效數據長度

public Myarray() {
// TODO Auto-generated constructor stub
array = new int[50];
}
public Myarray(int Maxsize) //重載構造方法
{
array = new int[Maxsize];
}

public void insert(int value) //插入數據

{
array[element] = value ;
element++;
}
public void display() //顯示數據
{
int i;
System.out.print("[");
for(i=0;i<element;i++)
{
System.out.print(array[i]+",");
}
System.out.println("]");
}

public void Search(int value) //按照數據找索引
{
int i;
for(i=0;i<element;i++)
{
if(array[i] == value)
break;
}
if(i == element)
System.out.println("error");
else
System.out.println(i);
}

public void searchB(int index) //按照索引找數據
{
if(index < 0 || index >element)
System.out.println("error");
else
System.out.println(array[index]);
}

public void delete(int index) //按照索引刪除數據
{
if(index < 0 || index >element)
System.out.println("error");
else
{
for(int i=index;i<element;i++)
{
array[i] =array[i+1];
}
element--;
}
}

public void update(int index,int value) //更新數據
{
array[index] = value;
}

一 自定義數組類