package com.company;
public class Array {
private int[] data;
private int size;
//构造函数,传入构造函数的容量来创建数组Array
public Array(int capacity){
data=new int[capacity];
size=0;
}
public Array(){
this(10);
}
public int getSize(){
return size;
}
public int getCapacity(){
return data.length;
}
public boolean isEmpty(){
return size==0;
}
public void addLast(int e){
add(size,e);
}
public void addFirst(int e){
add(0,e);
}
public void add(int index,int e){
if(size==data.length){
throw new IllegalArgumentException("add is failed");
}
if (index<0||index>size){
throw new IllegalArgumentException("add is failed");
}
for (int i=size-1;i>=index;i--){
data[i+1]=data[i];
data[index]=e;
size++;
}
}
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
res.append('[');
for(int i = 0 ; i < size ; i ++){
res.append(data[i]);
if(i != size - 1)
res.append(", ");
}
res.append(']');
return res.toString();
}
}
package com.company;
public class Main {
public static void main(String[] args) {
Array arr = new Array(20);
for(int i = 0 ; i < 10 ; i ++){
arr.addLast(i);
}
System.out.println(arr);
}
}
运行这个方法出现的是这个结论,怎么不能像视频里按顺序出现0到9呢?
Array: size = 0 , capacity = 20
[]