# 动态数组原理【Java实现】

## 集合入门

public class QueueDemo {

private int Size;

private Integer[] Elements;

}

public class QueueDemo {

// 数组大小
private int Size;

// 数组
private Integer[] Elements;

// 初始化数组容量
public QueueDemo(int capacity) {
Elements = new Integer[capacity];
}

}

    // 添加元素
Elements[Size] = element;
Size++;
}

  // 重写toString打印元素
@Override
public String toString() {
int length = Elements.length;
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < length; i++) {
sb.append(Elements[i]);
if (i != length - 1) {
sb.append(",");
}
}
return sb.toString();
}

public class Main {

public static void main(String[] args) {
QueueDemo demo = new QueueDemo(5);
System.out.println(demo);
}
}

public void Insert(int index, Integer element) {

}

// 删除元素
public void Remove(Integer element) {
int index = GetIndex(element);
for (int i = index; i < Elements.length - 1; i++) {
Elements[i] = Elements[i + 1];
}
Elements[Size - 1] = null;
Size--;
}

        //删除元素
demo.Remove(3);
System.out.println(demo);

因为我们将数组最后一位元素置为空，所以在打印时应删除，我们继续改造重写的toString方法，如下：

    @Override
public String toString() {
int length = Elements.length;
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < length; i++) {
if (Elements[i] == null) {
continue;
}
sb.append(Elements[i]);
if (i != length - 1) {
sb.append(",");
}
}
if (sb.charAt(sb.length() - 1) == ',') {
sb.delete(sb.length() - 1, sb.length());
}
sb.append("]");
return sb.toString();
}

接下来体育老师要求报数，比如根据某个同学的姓名即元素报出自己所在的第几位（也就对应数组中的索引），所以此时我们再封装一个获取指定元素的索引方法，如下：

// 获取指定元素索引
public int GetIndex(Integer element) {
for (int i = 0; i < Elements.length - 1; i++) {
if (!Elements[i].equals(element)) {
continue;
}
return i;
}
throw new RuntimeException("未找到");
}

System.out.println("4号同学所在的位置是 ：" + demo.GetIndex(4));

    public void Add(Integer element) {
if (Size >= Elements.length) {
Elements = Arrays.copyOf(Elements, 2 * Elements.length);
}
Elements[Size] = element;
Size++;
}
public static void main(String[] args) {
QueueDemo demo = new QueueDemo(5);
System.out.println(demo);
//删除元素
demo.Remove(3);
System.out.println(demo);
System.out.println("4号同学所在的位置是 ：" + demo.GetIndex(4));

System.out.println(demo); }

    private int DEFAULT_CAPACITY = 10;

public QueueDemo() {
Elements = new Integer[DEFAULT_CAPACITY];
}

public QueueDemo(int capacity) {
Elements = new Integer[capacity <= 0 ? DEFAULT_CAPACITY : capacity];
}

public void Insert(int index, Integer element) {
if (Size <= index || index < 0) {
throw new RuntimeException("超出数组边界");
}
System.arraycopy(Elements, index, Elements, index + 1,
Size - index);
System.out.println(this);
Elements[index] = element;
Size++;
}
        QueueDemo demo = new QueueDemo();
System.out.println(demo);
//删除元素
demo.Remove(3);
System.out.println(demo);
System.out.println("4号同学所在的位置是 ：" + demo.GetIndex(4));

System.out.println(demo);