@生活泠战士 #和我一起去战斗
还不会数组扩容的小伙伴赶紧和我一起来战斗吧!!!
public class MyArray {
/**
* 保存数据的数组
*/
private Object[] objects = null;
/**
* 默认元素的个数
*/
private int DEFAULT_LENGTH = 10;
/**
* 默认元素的个数
*/
private int size = 0;
/**
* 数组长度
*/
private int length;
/**
* 扩容数组的长度的参数
*/
private int LOAD=2;
/**
* 无参构造方法,初始化数组长度为默认长度
*/
public MyArray() {
length = DEFAULT_LENGTH;
objects = new Object[length];
}
public MyArray(int length) {
this.length = length;
objects = new Object[this.length];
}
/**
* 数组添加元素
*/
public void add(Object o) {
if (size == 0) {
objects[size] = 0;
size++;
} else {
objects[size] = o;
size++;
}
}
/**
* 重载add 在某个索引处添加元素,当索引小于0或者大于size是抛出异常
*/
public void add(int index, Object o) {
if (index < 0 || index > size) {
throw new ArrayIndexOutOfBoundsException("越界");
} else {
if (size==length) {
length=length*LOAD;
objects=Arrays.copyOf(objects, length);
}
System.arraycopy(objects, index, objects, index + 1, size - index);
objects[index] = o;
size++;
}
}
/**
* 根据索引删除元素
*/
public void remove(int index) {
if (index < 0 || index >= size) {
throw new ArrayIndexOutOfBoundsException("下标越界");
}
objects[index] = null;
System.arraycopy(objects, index + 1, objects, index, size - index);
size--;
}
/**
* 根据索引获取位置处的元素
*/
public Object get(int index) {
if (index < 0 || index > size) {
throw new ArrayIndexOutOfBoundsException("下表越界");
}
return objects[index];
}
/*
* 修改某一位位置处的元素
*/
public void update(int index, Object o) {
if (index < 0 || index > size) {
throw new ArrayIndexOutOfBoundsException("下标越界");
}
objects[index] = o;
}
/*
* 打印数组[1,2,3,4,5] null不打印
*/
public String toString() {
StringBuffer sb = new StringBuffer("[");
for (int i = 0; i < size; i++) {
sb.append(objects[i]);
sb.append(",");
}
sb.append("]");
return sb.toString().replace(",]", "]");
}
/*
* 获取数组内元素的个数
*/
public int size() {
return size;
}
/**
* 新增方法contains(Object o);判断是否存在改元素,如果存在返回索引,如果不存在返回-1
*/
public boolean contains(Object o) {
int i=indexof(o);
return i>=0?true:false;
}
/**
* 移除数组内所有元素,禁止使用for循环
*/
public void removeAll() {
System.out.println("size of MyArrays-----"+size);
// while (size > 0) {
// remove(size - 1);
// }
Arrays.fill(objects, null);
size=0;
}
/**
* 查找元素所在位置
*/
public int indexof(Object o) {
// if (size==0) {
// return size;
// }
// else if (size==length) {
// return -1
// }
// else if (size<length) {
// return size;
// }
if (o==null) {
return -1;
}else {
for (int i = 0; i <size; i++) {
if (o.equals(i)) {
return i;
}
}
}
return -1;
}
}