标签:row 实现类 动态数组 容器 on() 代码 == initial except
List 接口的大小可变数组的实现。实现了所有可选列表操作,并允许包括 null 在内的所有元素。除了实现 List 接口外,此类还提供一些方法来操作内部用来存储列表的数组的大小。
(Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.)
每个 ArrayList 实例都有一个容量。该容量是指用来存储列表元素的数组的大小。它总是至少等于列表的大小。随着向 ArrayList 中不断添加元素,其容量也自动增长。
(Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. )
1 public class MyArrayList { 2 private Object[] elementDate; 3 4 private int size; 5 6 public Object get(int index) { 7 if(index<0 || index>=size) { 8 try { 9 throw new Exception(); 10 } catch (Exception e) { 11 e.printStackTrace(); 12 } 13 } 14 return elementDate[index]; 15 } 16 17 public boolean isEmpty() { 18 return size == 0; 19 } 20 21 public int size() { 22 return size; 23 } 24 25 public MyArrayList(){ 26 this(10); //调用有参构造方法,初始化数组大小为10 27 } 28 public MyArrayList(int initialCapacity){ 29 if(initialCapacity<0){ 30 try { 31 throw new Exception(); 32 } catch (Exception e) { 33 e.printStackTrace(); 34 } 35 } 36 elementDate = new Object[initialCapacity]; 37 } 38 39 public void add(Object obj) { 40 if(size==elementDate.length) { 41 Object[] newArrayList = new Object[size*2+1]; //当数组达到上限,创建新的数组对象
//System.arraycopy(elementDate, 0, newArrayList, 0, elementDate.length); //使用arraycopy方法也没问题,代码更简洁 42 for(int i=0; i<newArrayList.length; i++) { 43 newArrayList[i] = elementDate[i]; //遍历旧数组元素,存入新数组 44 elementDate = newArrayList; //将新数组地址传递给旧数组 45 } 46 } 47 elementDate[size++] = obj; 48 }
常用容器(Collection)实现类总结(一)——ArrayList
标签:row 实现类 动态数组 容器 on() 代码 == initial except
原文地址:http://www.cnblogs.com/nothingAJ/p/6611648.html