赞
踩
- /**
- * 自己实现一个ArrayList,帮助我们更好地理解ArrayList类的底层结构
- * @author Administrator
- *
- */
- public class MyArrayList {
-
- private Object[] elementData;
- private int size;
-
- public MyArrayList(){
- this(10); //默认的数组长度为10
- }
-
- public MyArrayList(int initialCapacity){
- if(initialCapacity<0)
- try {
- throw new Exception();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- elementData = new Object[initialCapacity];
- }
-
- public int size(){
- return size;
- }
-
- public void ensureCapacity(){
- //若数组已满,则给数组扩容
- if(size==elementData.length){
- Object[] newArray = new Object[size*2];
- System.arraycopy(elementData, 0, newArray, 0, elementData.length);
- elementData = newArray;
- }
- }
-
- public void add(Object o){
- ensureCapacity();
- elementData[size]=o;
- size++;
- }
-
- public void add(int index, Object obj){
- rangeCheck(index);
- ensureCapacity();
- for(int i=size-1;i>=index;i--){
- elementData[i+1]=elementData[i];
- }
- elementData[index]=obj;
- size++;
- }
-
- public boolean isEmpty(){
- return size==0;
- }
-
-
- public Object get(int index){
- rangeCheck(index);
- return elementData[index];
- }
-
- public Object remove(int index){
- rangeCheck(index);
- Object deletedObject = elementData[index];
- //int numMoved = size-index-1;
- //System.arraycopy(elementData, index+1, elementData, index, numMoved);
- for(int i=index+1; i<this.size();i++){
- elementData[i-1]=elementData[i];
- }
- elementData[--size]=null;
- return deletedObject;
- }
-
- public boolean remove(Object obj){
- for(int i=0; i<this.size();i++){
- if(elementData[i].equals(obj)){
- remove(i);
- return true;
- }
- }
- return false;
- }
-
- public Object set(int index, Object obj){
- rangeCheck(index);
- Object oldValue=elementData[index];
- elementData[index]=obj;
- return oldValue;
- }
-
- private void rangeCheck(int index){
- if( index < 0 ||index >= size){
- try {
- throw new Exception();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
-
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- MyArrayList list = new MyArrayList(3);
- list.add(123);
- list.add("haha");
- list.add("wxxyy");
- list.add("you");
- System.out.println(list.get(3));
- }
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。