ArrayList内部实现是通过数组来完成的,由于数组在内存中是连续的储存单元,所以其添加元素和删除操作均通过System.arraycopy()
实现。ArrayList在查找读取操作时效率高;当涉及到数据经常进行增删操作时应使用LinkedList的数据结构更合适。
public class ArrayList<E>{
private Object[] element_data;
private int size;
private static final int DEFAULT_CAPACITY = 10;
public ArrayList() {
element_data = new Object[DEFAULT_CAPACITY];
}
public ArrayList(int capacity){
element_data = new Object[capacity];
}
public void add(E element){
if (element_data.length==size){
Object[] new_data = new Object[element_data.length*2];
System.arraycopy(element_data,0,new_data,0,element_data.length);
element_data = new_data;
}
element_data[size++] = element;
}
public E get(int index){
checkIndex(index);
return (E) element_data[index];
}
public void set(int index,E element) {
checkIndex(index);
element_data[index] = element;
}
private void checkIndex(int index) {
if (index<0 || index>size-1) {
throw new RuntimeException("index Error! at: "+ index);
}
}
//拷贝element_data自己
public void remove(int index) {
System.arraycopy(element_data,index+1,element_data,index,element_data.length-1-index);
size--;
}
public void remove(E element) {
for (int i=0;i<size;i++){
if (element.equals(get(i))){
remove(i);
}
}
}
public boolean isEmpty(){
return size==0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
//[a,b,c]
sb.append("[");
for (int i = 0; i <size ; i++) {
sb.append(element_data[i]);
sb.append(",");
}
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}
public static void main(String[] args){
ArrayList<Object> my = new ArrayList<>(1);
System.out.println(my.isEmpty());
System.out.println(my);
}
}
网友评论