如何构建一个我们自己使用的泛型数组 1.可以扩容 2.接收“任何”类型(基本数据类型使用包装类型 ) 3.增删改查
存储泛型数据
private E[] data;
private int size;
构造函数
public Array() {
this(10);
}
public Array(int capacity) {
data = (E[]) new Object[capacity];
this.size = 0;
}
new E[capacity];
扩容方法
扩容就是新建另一个数组,然后把当前数据拷贝到另一个数组中,然后data指向新数组
private void resize(int capacity) {
E[] newData = (E[]) new Object[capacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
data = newData;
}
}
插入数据方法
public void insert( int index , E e ) {
if (size == data.length){
resize(2 * data.length);
}
if (index < 0 || index > size){
throw new IllegalArgumentException("添加失败,索引参数有误");
}
for (int i = size-1; i >= index; i--) {
data[i+1] = data[i];
}
data[index] = e;
size++;
}
在for循环中,我们是从数组的后端,把每个元素都后移一位 。 为什么i是从size-1开始,会不会数组越界 size是数组的元素个数,在上一次添加时,就已经有了size个元素了(当前的元素没有添加进去,共有size个数,第size+1个数,即索引为size) 全部代码
public class Array<E> {
private E[] data;
private int size;
public Array() {
this(10);
}
public Array(int capacity) {
data = (E[]) new Object[capacity];
this.size = 0;
}
public void addLast(E e){
insert(size,e);
}
private void resize(int capacity) {
E[] newData = (E[]) new Object[capacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
data = newData;
}
}
public void insert( int index , E e ) {
if (size == data.length){
resize(2 * data.length);
}
if (index < 0 || index > size){
throw new IllegalArgumentException("添加失败,索引参数有误");
}
for (int i = size-1; i >= index; i--) {
data[i+1] = data[i];
}
data[index] = e;
size++;
}
public E get(int index){
if (index < 0 || index >= size){
throw new IllegalArgumentException("获取数据失败,索引有误");
}
return data[index];
}
public void set(int index , E e ){
if (index < 0 || index >= size){
throw new IllegalArgumentException("获取数据失败,索引有误");
}
data[index] = e;
}
public boolean contains(E e){
for (int i = 0; i < size; i++) {
if (data[i] == e){
return true;
}
}
return false;
}
public int find(E e){
for (int i = 0; i < size; i++) {
if (data[i] == e){
return i;
}
}
return -1;
}
public E remove( int index ){
if (index < 0 || index >= size){
throw new IllegalArgumentException("获取数据失败,索引有误");
}
E deleteE = data[index];
for (int i = index+1; i > size ; i--) {
data[i-1] = data[i];
}
size--;
return deleteE;
}
public E removeFirst(){
return remove(0);
}
public E removeLast(){
return remove(size-1);
}
public void removeElement(E e){
int index = find(e);
if (index != -1){
remove(index);
}
}
public boolean isEmpty(){
return size == 0;
}
public int getSize(){
return size;
}
public int getCapacity(){
return data.length;
}
@Override
public String toString() {
StringBuilder stringBuilder=new StringBuilder();
for (int i = 0; i < size; i++) {
stringBuilder.append(i+" ");
}
return "Array{" +
"data = " + stringBuilder.toString() +
", size = " + size +
'}' +
"capacity = " + data.length;
}
}
|