如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 |
package com.soto.collection;
/** * 自己实现一个ArrayList,帮助我们更好地理解ArrayList的底层结构; * @author 王 * */ public class SxtArrayList { private Object[] elementData; private int size; public int size(){ return size; } public boolean isEmpty(){ return size == 0 ; }
public SxtArrayList(){ this ( 10 ); } public SxtArrayList( int initialCapacity){ if (initialCapacity< 0 ){ try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } elementData = new Object[initialCapacity]; //初始化 容量为10
} public void add(Object obj){ elementData[size++] = obj; //若超过容量了,那么..数组扩容 if (size==elementData.length){ //实质:搞个新数组 Object[] newarray = new Object[size* 2 + 1 ]; //数组的copy: System.arraycopy(elementData, 0 , newarray, 0 , elementData.length); elementData = newarray;
}
} public Object get( int index){ rangeCheck(index); return elementData[index]; } public void remove( int index){ rangeCheck(index);
//删除指定位置对象,删除某位置,相当于 将后往前挪: int numMoved = size-index- 1 ; if (numMoved> 0 ){ System.arraycopy(elementData, index+ 1 , elementData, index, numMoved); } } public void remove(Object obj){ for ( int i= 0 ;i<size;i++){ if (get(i).equals(obj)){ //注意底层调用的equals方法而不是==。 remove(i); } } }
private void rangeCheck( int index){ if (index< 0 ||index>size){ try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } }
} public Object set( int index, Object obj){ rangeCheck(index); Object oldValue = elementData[index]; elementData[index] = obj; return oldValue;
} public void add( int index, Object obj){ rangeCheck(index); ensureCapacity(); //扩容 System.arraycopy(elementData, index, elementData, index + 1 , size - index); elementData[index] = obj; size++;
} private void ensureCapacity(){ //扩容 if (size==elementData.length){ //实质:搞个新数组 Object[] newarray = new Object[size* 2 + 1 ]; //数组的copy: System.arraycopy(elementData, 0 , newarray, 0 , elementData.length); elementData = newarray; } }
public static void main(String[] args) { SxtArrayList list = new SxtArrayList( 3 ); list.add( "222" ); list.add( "333" ); list.add( "444" ); list.add( "555" ); list.add( "666" ); list.add( "777" ); System.out.println(list.size()); System.out.println(list.get( 6 )); }
} |
以上这篇Java ArrayList的底层实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/u013511642/article/details/70952949
查看更多关于Java ArrayList的底层实现方法的详细内容...