基于面向对象思维(封装)实现一个动态数组(MyArray)
- 能够无限的向数组中添加元素
- 可以通过get方法获取指定位置的元素
- 可以通过size方法获取数组中元素的个数
- 可以通过remove方法删除数组中的指定元素
package work2;
public class MyArray {
int[] array;
boolean fisttime=true;
public MyArray() {
this.array = new int[1];
}
int size(){
return this.array.length;
}
void addspace(){
this.array=new int[this.array.length+1];
}
void delspace(){
this.array=new int[this.array.length-1];
}
void add(int n) {
if(this.fisttime){
this.array[0]=n;
this.fisttime=false;
}else{
int[] rec = new int[this.array.length];
for (int i = 0; i < this.array.length; i++) {
rec[i] = this.array[i];
}
this.addspace();
for (int i = 0; i < this.array.length-1; i++) {
this.array[i] = rec[i];
}
this.array[this.array.length-1] = n;
}
}
void get(int n){
n--;
for(int i=0;i<this.size();i++){
if(i==n){
System.out.println("该位置数据为:"+this.array[i]);
}
}
}
void remove(int n){
int[] rec = new int[this.array.length-1];
for(int i=0;i<this.size();i++){
if(i<n){
rec[i]=this.array[i];
}else if(i==n){
break;
}
}
for(int i=0;i<this.size();i++){
if(i>n){
rec[i-1]=this.array[i];
}
}
this.delspace();
for(int i=0;i<rec.length;i++){
this.array[i]=rec[i];
}
}
public static void main(String[] args) {
MyArray ma = new MyArray();
ma.add(1);
ma.add(2);
ma.add(3);
for(int a:ma.array){
System.out.println(a);
}
ma.get(2);
System.out.println("目前数组长度为:"+ma.size());
ma.remove(2);
for(int a:ma.array){
System.out.println(a);
}
}
}