数据结构(三)面向对象的数组
package demo01;
import java.util.Arrays;
public class MyArray {
private int[] elements;
public MyArray(){
elements =new int[0];
}
public int size(){
return elements.length;
}
public void add(int element){
int[] newArr = new int[elements.length+1];
for(int i=0;i<elements.length;i++){
newArr[i]=elements[i];
}
newArr[elements.length]=element;
elements=newArr;
}
public void show(){
System.out.println(Arrays.toString(elements));
}
public void delete(int index){
if(index < 0 || index > elements.length-1){
throw new RuntimeException("下标越界");
}
int[] newArr=new int[elements.length-1];
for(int i=0; i<newArr.length; i++){
if(i<index){
newArr[i]=elements[i];
}else {
newArr[i]=elements[i+1];
}
}
elements=newArr;
}
public int get(int index){
return elements[index];
}
public void insert(int index, int element){
int[] newArr = new int[elements.length+1];
for(int i=0; i<elements.length; i++){
if(i<index){
newArr[i]=elements[i];
}else {
newArr[i+1]=elements[i];
}
}
newArr[index]=element;
elements=newArr;
}
}
测试
package demo01;
import demo01.MyArray;
public class TestArray {
public static void main(String[] args) {
MyArray ma=new MyArray();
int size= ma.size();
ma.show();
ma.add(9);
ma.add(99);
ma.add(58);
ma.show();
ma.delete(0);
ma.show();
int i = ma.get(1);
System.out.println("i:"+i);
ma.insert(1,85);
ma.show();
ma.insert(1,54);
ma.show();
}
}
|