SuperArray功能,存储int型的数值,如果超过,则默认以当前空间二倍扩展,如果传入了增长参数,则增加传入的参数数值容量。
SuperArray.java:
package com.zmz.work;
/**
* 长度可变的数组(ctrl + s + f)
*
* @author zmz
*
*/
public class SuperArray {
/**
* 容量(容器的大小)
*/
private int capacity;
/**
* 大小(元素的个数)
*/
private int size = 0;
/**
* 数据
*/
private int[] data;
/**
* 容量的增量(步长)默认为0
*/
private int increment = 0;
/**
* 容量为 10 线性表
*/
public SuperArray() {
this(10);
}
/**
* 创建指定大小的容器
*
* @param capacity
* 默认的容量
*/
public SuperArray(int capacity) {
this.capacity = capacity;
data = new int[capacity];
}
// 构造器模式
// public SuperArray(int increment) {
//
// }
/**
* 创建变长数组
*
* @param capacity
* 容量
* @param increment
* 扩容的增长因子
*/
public SuperArray(int capacity, int increment) {
this(capacity);
this.increment = increment;
}
/**
* 获得容器的大小(存储的元素的个数)
*
* @return int 小于等于容量
*/
public int getSize() {
return size;
}
/**
* 获得容器的容量
*
* @return int 容器的容量
*/
public int getCapacity() {
return capacity;
}
/**
* 往容器中(末尾)添加一个元素
*
* @param n
* int 要存入容器的元素
*/
public void add(int n) {
// 检查容量与元素的数量
// 设计模式、重构、架构模式设计
increaseCapacity();
data[size++] = n;
}
/**
* 在指定位置添加信息元素
*
* @param index
* 新元素的位置(索引、0为起点)
* @param n
* 添加的新元素
*/
public boolean add(int index, int n) {
if (index > size) {
return false;
}
data[index] = n;
return true;
}
/**
* 获得指定位置的元素
*
* @param index
* @return
*/
public int get(int index) {
// TODO
return data[index];
}
/**
* 删除特定位置的元素
*
* @param index 位置
* @return
*/
public int remove(int index) {
// TODO
return 0;
}
/**
* 扩容
*/
private void increaseCapacity() {
if (size == capacity) {
// 扩容
if (increment == 0) {
capacity *= 2;
} else {
capacity += increment;
}
int[] newData = new int[capacity];
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
System.out.println("扩容为:" + capacity);
}
}
public void show() {
System.out.printf("\n容量:%d, 大小:%d\n", capacity, size);
for (int i = 0; i < size; i++) {
System.out.print(data[i] + ",");
}
}
}
Test.java:
package com.zmz.work;
public class Test {
// alt + /
public static void main(String[] args) {
SuperArray a1 = new SuperArray(15);
SuperArray a2 = new SuperArray(17);
SuperArray a3 = new SuperArray(10);
SuperArray a4 = new SuperArray(10,3);
for (int i = 0; i < 15; i++) {
a1.add(i);
a2.add(i);
a3.add(i);
a4.add(i);
}
a1.show();
a2.show();
a3.show();
a4.show();
}
}
输出:
扩容为:20
扩容为:13
扩容为:16
容量:15, 大小:15
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
容量:17, 大小:15
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
容量:20, 大小:15
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
容量:16, 大小:15
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
扩容为:13
扩容为:16
容量:15, 大小:15
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
容量:17, 大小:15
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
容量:20, 大小:15
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,
容量:16, 大小:15
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,