package mycollection;
/**
- 1自定义实现一个ArrayList
- 2增加泛型
- 3增加数组扩容
- 4增加set和get方法
- 增加:数组边界的检查
- 5增加remove方法
- @author
*/
public class TestArrayList {
private Object[] elementDate;
private int size;
private static final int DEFALT_CAPACITY = 10;
public TestArrayList5() {
elementDate = new Object[DEFALT_CAPACITY];
}
public TestArrayList5(int a){
if(a<0){
throw new RuntimeException("容器容量不能为负数");
}else if(a == 0){
elementDate = new Object[DEFALT_CAPACITY];
}else{
elementDate = new Object[a];
}
}
public int size(){
return size;
}
public boolean isEmpty(){
return size==0?true:false;
}
public void add(E e){
//什么时候扩容
if(size == elementDate.length ){
//扩容
Object[] newArray = new Object[elementDate.length+(elementDate.length>>1)];//elementDate.length>>1 要括起来 加法的优先级高
System.arraycopy(elementDate, 0, newArray, 0, elementDate.length);
elementDate = newArray;
}
elementDate[size++] = e;
}
public E get(int index){
return (E)elementDate[index];
}
public void set(E e,int index){
checkRange(index);
elementDate[index] = e;
}
public void checkRange(int index){//检查范围
//索引判断[0,size)
if(index<0 || index>size){
//不合法
throw new RuntimeException("索引不合法!");
}
}
public void remove(E e){
//e将它和所有元素进行比较 获得第一个为true的 返回
for(int i=0; i<size; i++){
if(e.equals(get(i))){ //容器中所有的比较操作都使用equals
//将该元素从此处移除
remove(i);
}
}
}
public void remove(int index){
int mumMoved = elementDate.length-index-1;
if(mumMoved>0){
System.arraycopy(elementDate, index+1, elementDate, index, mumMoved);
}
elementDate[--size] = null;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
//[a,b,c]
sb.append("[");
for(int i=0; i<size; i++){
sb.append(elementDate[i]+",");
}
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}
public static void main(String[] args) {
TestArrayList5<String> a1 = new TestArrayList5<>();
for(int i=0; i<10; i++){
a1.add("a"+i);
}
a1.set("aaaa", 3);
System.out.println(a1);
System.out.println(a1.get(3));
a1.remove("aaaa");
a1.remove(1);
System.out.println(a1);
System.out.println(a1.size);
System.out.println(a1.isEmpty());
}
}