1 //ArrayList增、删、查代码具体实现 2 3 package com.coding.basic; 4 5 import java.util.Arrays; 6 7 public class MyArrayList implements List { 8 9 private static final int DEFAULT_CAPACITY = 10; 10 private int size = 0; 11 12 Object[] elementData; 13 14 // 默认数组容量是10 15 public MyArrayList() { 16 this(DEFAULT_CAPACITY); 17 } 18 19 // 传入数组容量 20 public MyArrayList(int capacity) { 21 22 if (capacity < 0) { 23 24 throw new IllegalArgumentException("Illegal Capacity: " + capacity); 25 } 26 if (capacity >= 0) { 27 elementData = new Object[capacity]; 28 size = elementData.length; 29 } 30 } 31 32 // 保证数组容量 33 private void ensurecapacity(int mincapacity) { 34 35 int oldcapacity = elementData.length; 36 if (mincapacity > oldcapacity) { 37 Object olddata[] = elementData; 38 // 1.5倍括容是最好的倍數 39 int newcapacity = oldcapacity * 3 / 2; 40 41 if (mincapacity > newcapacity) { 42 newcapacity = mincapacity; 43 } 44 elementData = Arrays.copyOf(elementData, newcapacity); 45 } 46 47 } 48 49 // 在尾部添加元素 50 public void add(Object o) { 51 ensurecapacity(size + 1); 52 elementData[size++] = o; 53 54 } 55 56 // 在任意位置添加元素 57 public void add(int index, Object o) { 58 RangeCheck(index); 59 ensurecapacity(size + 1); 60 for (int x = size - 1; x > index; x--) { 61 elementData[x + 1] = elementData[x]; 62 63 } 64 elementData[index + 1] = o; 65 } 66 67 // 获取任意位置上的元素 68 public Object get(int index) { 69 RangeCheck(index); 70 71 return elementData[index]; 72 73 } 74 75 // 检查索引值范围 76 private void RangeCheck(int index) { 77 if (index < 0 || index >= size) { 78 throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); 79 } 80 81 } 82 83 // 删除任意位置元素并返回该元素 84 public Object remove(int index) { 85 return remove(index, elementData); 86 } 87 88 // 删除任意位置元素并返回该元素 89 public Object remove(int index, Object[] elementData) { 90 RangeCheck(index); 91 if (index >= 0 && index < size - 1) { 92 for (int i = index; i < size - 1; i++) { 93 elementData[i] = elementData[i + 1]; 94 95 } 96 97 } 98 if (index == size - 1) { 99 elementData[index] = elementData[size - 1]; 100 } 101 102 size--; 103 return elementData[index]; 104 } 105 106 // 获取数组长度 107 public int size() { 108 return size; 109 } 110 111 }
时间: 2024-10-16 07:47:24