如下所示:
- 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的底层实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持w3xue。