复制代码
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
83package com.kgc; public class SxtArrayList02<E> { private Object[] elementData; private int size; // 默认长度 private static final int DEFAULT_CAPACITY = 10; // 无参构造 public SxtArrayList02() { elementData = new Object[DEFAULT_CAPACITY]; } // 有参构造 public SxtArrayList02(int capacity) { if (capacity < 0) { throw new RuntimeException("容量的大小不能为负数"); } else if (capacity == 0) { elementData = new Object[DEFAULT_CAPACITY]; } else { elementData = new Object[capacity]; } } public int size() { return size; } public boolean isEmpty() { return size==0?true:false; } public void add(E element) { // 什么时候扩容?? if (size == elementData.length) { // 怎么扩容 Object[] newArray = new Object[elementData.length + (elementData.length >> 1)];// 10-->10+10/2 System.arraycopy(elementData, 0, newArray, 0, elementData.length); elementData = newArray; } elementData[size++] = element; } public E get(int index) { checkRange(index); return (E) elementData[index]; } public void set(E element, int index) { checkRange(index); elementData[index] = element; } public void checkRange(int index) { // 索引合法判断[0,size) if (index < 0 || index > size - 1) { // 不合法 throw new RuntimeException("索引不合法:" + index); } } public void remove(E element) { //element,将它和所有元素挨个比较,获得第一个比较为true的,返回。 for(int i = 0;i<size;i++) { if(element.equals(get(i))) {//容器中所有的比较操作,都是用的equals而不是== //将该元素从此处移除 remove(i); } } } public void remove(int index) { //a,b,c,d,e,f,g,h //a,b,c,e,g,f,h int numMoved = elementData.length-index-1; if(numMoved>0) { System.arraycopy(elementData, index+1, elementData, index, numMoved); } elementData[--size] = null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < size; i++) { sb.append(elementData[i] + ","); } sb.setCharAt(sb.length() - 1, ']'); return sb.toString(); } public static void main(String[] args) { } }
最后
以上就是瘦瘦菠萝最近收集整理的关于手工实现ArrayList的全部内容,更多相关手工实现ArrayList内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复