服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - JAVA提高第十篇 ArrayList深入分析

JAVA提高第十篇 ArrayList深入分析

2021-01-28 12:07pony1223 Java教程

这篇文章主要深入分析了JAVA提高第十篇ArrayList的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

前面一章节,我们介绍了集合的类图,那么本节将学习collection 接口中最常用的子类arraylist类,本章分为下面几部分讲解(说明本章采用的jdk1.6源码进行分析,因为个人认为虽然jdk1.8进行了部分改动,但万变不离其宗,仍然采用的jdk1.6的引子进行的优化,因此学会了1.6对于1.8也就理解了)。

一、arraylist 的常见功能

在分析arraylist的源码前,我们先看下arraylist的常见的功能:

?
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
package study.collection;
 
import java.util.arraylist;
import java.util.date;
import java.util.list;
 
public class testdemo01
{
 public static void main(string[] args)
 {
  list list = new arraylist();
  //arraylist:底层实现时数组,线程不安全,效率高。所以,查询快。修改、插入、删除慢。
  //linkedlist:底层实现是链表,线程不安全,效率高。所以,查询慢。修改、插入、删除快。
  //vector:线程安全的,效率低。
  
  list.add("aaa");
  list.add("aaa");
  list.add(new date());
  list.add(new dog());
  list.add(1234); //注意,list集合中只能添加引用类型,这里包装类的:自动装箱!
  list.remove(new string("aaa"));
  system.out.println(list.size());
  for(int i=0;i<list.size();i++){
   system.out.println(list.get(i));
  }
  
  list.set(3, new string("3333"));
  list.add(4, new string("3333"));
  
  system.out.println(list.isempty());
  list.remove(new dog());  //hashcode和equals
  system.out.println(list.size());
  
  list list2 = new arraylist();
  list2.add("bbb");
  list2.add("ccc");
  
  list.add(list2);
  
  //跟顺序的操作
  string str = (string) list.get(0);
  system.out.println(str);
  list.set(1, "ababa");
  list.remove(0);
 }
 
}
 
class dog
{
}

从上述可以看到了,arraylist 接口中除了继承自父类collection 接口中的方法外,还实现了list接口中扩充的和索引相关的方法,这都源于其底层为数组结构。

二、arraylist 的重要的属性

上面的部分列举了arraylist中常见的一些功能方法,那么这些方法又是如何使用的呢,下面我们将进行源码的剖析,在剖析前,我们可以自己思考下,我们知道arraylist 是一个动态扩展的集合,之所以动态扩展的原因或者说比数组强的地方肯定就在于数组的长度是固定的,不能扩展,这是数组的最大缺陷,所以才有了集合,那么arraylist,那么其底层肯定也采用的是数组结构,因为它叫arraylist嘛,那么其重要的属性之一,必然是定义了一个数组。如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class arraylist<e> extends abstractlist<e>
  implements list<e>, randomaccess, cloneable, java.io.serializable
{
 private static final long serialversionuid = 8683452581122892189l;
 
 /**
  * the array buffer into which the elements of the arraylist are stored.
  * the capacity of the arraylist is the length of this array buffer.
  */
 private transient object[] elementdata;
 
 /**
  * the size of the arraylist (the number of elements it contains).
  *
  * @serial
  */
 private int size;

arraylist就是一个以数组形式实现的集合,其元素的功能为:

private transient object[] elementdata;    //arraylist是基于数组的一个实现,elementdata就是底层的数组

private int size;   //arraylist里面元素的个数,这里要注意一下,size是按照调用add、remove方法的次数进行自增或者自减的,所以add了一个null进入arraylist,size也会加1

三、arraylist 的构造方法分析

在分析完上面的属性后,我们紧接着来看下arraylist的构造方法:

?
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
/**
 *构造一个具有指定容量的list
 */
public arraylist(int initialcapacity) {
super();
 if (initialcapacity < 0)
  throw new illegalargumentexception("illegal capacity: "+
           initialcapacity);
this.elementdata = new object[initialcapacity];
}
 
/**
 * 构造一个初始容量为10的list,也就说当我们经常采用new arraylist()的时候,实际分配的大小就为10
 */
public arraylist() {
this(10);
}
 
/**
 *构造一个包含指定元素的list,这些元素的是按照collection的迭代器返回的顺序排列的
 */
public arraylist(collection<? extends e> c) {
elementdata = c.toarray();
size = elementdata.length;
// c.toarray might (incorrectly) not return object[] (see 6260652) 这里是因为toarray可能不一定是object类型的,因此判断如果不是就进行了拷贝转换操作
if (elementdata.getclass() != object[].class)
 elementdata = arrays.copyof(elementdata, size, object[].class);
}

可以看到,arraylist 提供了三个构造方法,分别的含义,已经注释到代码上面了,那么想一下指定容量的构造方法的意义,既然默认为10就可以那么为什么还要提供一个可以指定容量大小的构造方法呢?思考下,下面会说到。

四、arraylist 的常见方法分析

1.add 添加元素

JAVA提高第十篇 ArrayList深入分析

 添加的方法,共有四个,下面我们分别分析下其功能源码:

?
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
/**
  *添加一个元素
  */
 public boolean add(e e)
 {
  // 进行扩容检查
  ensurecapacity(size + 1); // increments modcount!!
  //将e增加至list的数据尾部,容量+1
  elementdata[size++] = e;
  return true;
 }
 
 
  /**
  *在指定位置添加一个元素
  */
 public void add(int index, e element) {
   // 判断索引是否越界
 if (index > size || index < 0)
  throw new indexoutofboundsexception(
  "index: "+index+", size: "+size);
// 进行扩容检查
 ensurecapacity(size+1); // increments modcount!!
  // 对数组进行复制处理,目的就是空出index的位置插入element,并将index后的元素位移一个位置
 system.arraycopy(elementdata, index, elementdata, index + 1,
    size - index);
 // 将指定的index位置赋值为element
 elementdata[index] = element;
  // list容量+1
 size++;
 }
 
 
 /**
  *增加一个集合元素
  */
 public boolean addall(collection<? extends e> c) {
  //将c转换为数组
 object[] a = c.toarray();
  int numnew = a.length;
  //扩容检查
 ensurecapacity(size + numnew); // increments modcount
 //将c添加至list的数据尾部
  system.arraycopy(a, 0, elementdata, size, numnew);
   //更新当前容器大小
  size += numnew;
 return numnew != 0;
 }
 
 
 /**
  * 在指定位置,增加一个集合元素
  */
 public boolean addall(int index, collection<? extends e> c) {
 if (index > size || index < 0)
  throw new indexoutofboundsexception(
  "index: " + index + ", size: " + size);
 
 object[] a = c.toarray();
 int numnew = a.length;
 ensurecapacity(size + numnew); // increments modcount
 
 // 计算需要移动的长度(index之后的元素个数)
 int nummoved = size - index;
  // 数组复制,空出第index到index+numnum的位置,即将数组index后的元素向右移动numnum个位置
 if (nummoved > 0)
  system.arraycopy(elementdata, index, elementdata, index + numnew,
     nummoved);
// 将要插入的集合元素复制到数组空出的位置中
  system.arraycopy(a, 0, elementdata, index, numnew);
 size += numnew;
 return numnew != 0;
 }
 
 
 /**
  * 数组容量检查,不够时则进行扩容
  */
 public void ensurecapacity( int mincapacity) {
  modcount++;
  // 当前数组的长度
  int oldcapacity = elementdata.length;
  // 最小需要的容量大于当前数组的长度则进行扩容
  if (mincapacity > oldcapacity) {
   object olddata[] = elementdata;
   // 新扩容的数组长度为旧容量的1.5倍+1
   int newcapacity = (oldcapacity * 3)/2 + 1;
   // 如果新扩容的数组长度还是比最小需要的容量小,则以最小需要的容量为长度进行扩容
   if (newcapacity < mincapacity)
    newcapacity = mincapacity;
   // mincapacity is usually close to size, so this is a win:
   // 进行数据拷贝,arrays.copyof底层实现是system.arraycopy()
   elementdata = arrays.copyof(elementdata, newcapacity);
  }
 }

2.remove 删除

?
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
/**
  * 根据索引位置删除元素
  */
 public e remove(int index) {
  // 数组越界检查
  rangecheck(index);
 
  modcount++;
  // 取出要删除位置的元素,供返回使用
  e oldvalue = (e) elementdata[index];
  // 计算数组要复制的数量
  int nummoved = size - index - 1;
  // 数组复制,就是将index之后的元素往前移动一个位置
  if (nummoved > 0)
   system. arraycopy(elementdata, index+1, elementdata, index,
       nummoved);
  // 将数组最后一个元素置空(因为删除了一个元素,然后index后面的元素都向前移动了,所以最后一个就没用了),好让gc尽快回收
  // 不要忘了size减一
  elementdata[--size ] = null; // let gc do its work
 
  return oldvalue;
 }
 
 /**
  * 根据元素内容删除,只删除匹配的第一个
  */
 public boolean remove(object o) {
  // 对要删除的元素进行null判断
  // 对数据元素进行遍历查找,知道找到第一个要删除的元素,删除后进行返回,如果要删除的元素正好是最后一个那就惨了,时间复杂度可达o(n) 。。。
  if (o == null) {
   for (int index = 0; index < size; index++)
    // null值要用==比较
    if (elementdata [index] == null) {
     fastremove(index);
     return true;
    }
  } else {
   for (int index = 0; index < size; index++)
    // 非null当然是用equals比较了
    if (o.equals(elementdata [index])) {
     fastremove(index);
     return true;
    }
  }
  return false;
 }
 
 /*
  * private remove method that skips bounds checking and does not
  * return the value removed.
  */
 private void fastremove(int index) {
  modcount++;
  // 原理和之前的add一样,还是进行数组复制,将index后的元素向前移动一个位置,不细解释了,
  int nummoved = size - index - 1;
  if (nummoved > 0)
   system. arraycopy(elementdata, index+1, elementdata, index,
        nummoved);
  elementdata[--size ] = null; // let gc do its work
 }
 
 /**
  * 数组越界检查
  */
 private void rangecheck(int index) {
  if (index >= size )
   throw new indexoutofboundsexception(
    "index: "+index+", size: " +size);
 }

分析:

增加和删除方法到这里就解释完了,代码是很简单,主要需要特别关心的就两个地方:1.数组扩容,2.数组复制,这两个操作都是极费效率的,最惨的情况下(添加到list第一个位置,删除list最后一个元素或删除list第一个索引位置的元素)时间复杂度可达o(n)。

还记得上面那个坑吗(为什么提供一个可以指定容量大小的构造方法 )?看到这里是不是有点明白了呢,简单解释下:如果数组初试容量过小,假设默认的10个大小,而我们使用arraylist的主要操作时增加元素,不断的增加,一直增加,不停的增加,会出现上面后果?那就是数组容量不断的受挑衅,数组需要不断的进行扩容,扩容的过程就是数组拷贝system.arraycopy的过程,每一次扩容就会开辟一块新的内存空间和数据的复制移动,这样势必对性能造成影响。那么在这种以写为主(写会扩容,删不会缩容)场景下,提前预知性的设置一个大容量,便可减少扩容的次数,提高了性能。

数组扩容伴随着开辟新建的内存空间以创建新数组然后进行数据复制,而数组复制不需要开辟新内存空间,只需将数据进行复制。

上面讲增加元素可能会进行扩容,而删除元素却不会进行缩容,如果在已删除为主的场景下使用list,一直不停的删除而很少进行增加,那么会出现什么情况?再或者数组进行一次大扩容后,我们后续只使用了几个空间,会出现上面情况?当然是空间浪费啦啦啦,怎么办呢?

?
1
2
3
4
5
6
7
8
9
10
11
/**
  * 将底层数组的容量调整为当前实际元素的大小,来释放空间。
  */
 public void trimtosize() {
  modcount++;
  // 当前数组的容量
  int oldcapacity = elementdata .length;
  // 如果当前实际元素大小 小于 当前数组的容量,则进行缩容
  if (size < oldcapacity) {
   elementdata = arrays.copyof( elementdata, size );
  }

3.更新 set

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
  * 将指定位置的元素更新为新元素
  */
 public e set( int index, e element) {
  // 数组越界检查
  rangecheck(index);
 
  // 取出要更新位置的元素,供返回使用
  e oldvalue = (e) elementdata[index];
  // 将该位置赋值为行的元素
  elementdata[index] = element;
  // 返回旧元素
  return oldvalue;
 }

4.查找

?
1
2
3
4
5
6
7
8
/**
  * 查找指定位置上的元素
  */
 public e get( int index) {
  rangecheck(index);
 
  return (e) elementdata [index];
 }

由于arraylist使用数组实现,更新和查找直接基于下标操作,变得十分简单。

5.是否包含.

?
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
/**
  * returns <tt>true</tt> if this list contains the specified element.
  * more formally, returns <tt>true</tt> if and only if this list contains
  * at least one element <tt>e</tt> such that
  * <tt>(o==null ? e==null : o.equals(e))</tt>.
  *
  * @param o element whose presence in this list is to be tested
  * @return <tt> true</tt> if this list contains the specified element
  */
 public boolean contains(object o) {
  return indexof(o) >= 0;
 }
 
 /**
  * returns the index of the first occurrence of the specified element
  * in this list, or -1 if this list does not contain the element.
  * more formally, returns the lowest index <tt>i</tt> such that
  * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
  * or -1 if there is no such index.
  */
 public int indexof(object o) {
  if (o == null) {
   for (int i = 0; i < size; i++)
    if (elementdata [i]==null)
     return i;
  } else {
   for (int i = 0; i < size; i++)
    if (o.equals(elementdata [i]))
     return i;
  }
  return -1;
 }
 
 /**
  * returns the index of the last occurrence of the specified element
  * in this list, or -1 if this list does not contain the element.
  * more formally, returns the highest index <tt>i</tt> such that
  * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
  * or -1 if there is no such index.
  */
 public int lastindexof(object o) {
  if (o == null) {
   for (int i = size-1; i >= 0; i--)
    if (elementdata [i]==null)
     return i;
  } else {
   for (int i = size-1; i >= 0; i--)
    if (o.equals(elementdata [i]))
     return i;
  }
  return -1;
 }

 contains主要是检查indexof,也就是元素在list中出现的索引位置也就是数组下标,再看indexof和lastindexof代码是不是很熟悉,没错,和public booleanremove(object o) 的代码一样,都是元素null判断,都是循环比较。

6.容量判断

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
  * returns the number of elements in this list.
  *
  * @return the number of elements in this list
  */
 public int size() {
  return size ;
 }
 
 /**
  * returns <tt>true</tt> if this list contains no elements.
  *
  * @return <tt> true</tt> if this list contains no elements
  */
 public boolean isempty() {
  return size == 0;
 }

说明:modcount 是干什么的,怎么到处都在操作这个变量,还有遍历呢,为啥不讲?由于iterator遍历相对比较复杂,而且iterator 是gof经典设计模式比较重要的一个,之后会对iterator单独分析。

五、transient 分析  和 arraylist的优缺点

1.arraylist的优缺点

1、arraylist底层以数组实现,是一种随机访问模式,再加上它实现了randomaccess接口,因此查找也就是get的时候非常快

2、arraylist在顺序添加一个元素的时候非常方便,只是往数组里面添加了一个元素而已

不过arraylist的缺点也十分明显:

1、删除元素的时候,涉及到一次元素复制,如果要复制的元素很多,那么就会比较耗费性能

2、插入元素的时候,涉及到一次元素复制,如果要复制的元素很多,那么就会比较耗费性能

因此,arraylist比较适合顺序添加、随机访问的场景。

2.arraylist和vector的区别

arraylist是线程非安全的,这很明显,因为arraylist中所有的方法都不是同步的,在并发下一定会出现线程安全问题。那么我们想要使用arraylist并且让它线程安全怎么办?一个方法是用collections.synchronizedlist方法把你的arraylist变成一个线程安全的list,比如:

?
1
2
3
4
5
6
7
list<string> synchronizedlist = collections.synchronizedlist(list);
synchronizedlist.add("aaa");
synchronizedlist.add("bbb");
for (int i = 0; i < synchronizedlist.size(); i++)
{
 system.out.println(synchronizedlist.get(i));
}

另一个方法就是vector,它是arraylist的线程安全版本,其实现90%和arraylist都完全一样,区别在于:

1、vector是线程安全的,arraylist是线程非安全的

2、vector可以指定增长因子,如果该增长因子指定了,那么扩容的时候会每次新的数组大小会在原数组的大小基础上加上增长因子;如果不指定增长因子,那么就给原数组大小

3.为什么arraylist的elementdata是用transient修饰的?

?
1
private transient object[] elementdata;

为什么elementdata是使用transient修饰的呢?我们看一下arraylist的定义:

?
1
2
public class arraylist<e> extends abstractlist<e>
  implements list<e>, randomaccess, cloneable, java.io.serializable

看到arraylist实现了serializable接口,这意味着arraylist是可以被序列化的,用transient修饰elementdata意味着我不希望elementdata数组被序列化。这是为什么?因为序列化arraylist的时候,arraylist里面的elementdata未必是满的,比方说elementdata有10的大小,但是我只用了其中的3个,那么是否有必要序列化整个elementdata呢?显然没有这个必要,因此arraylist中重写了writeobject方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void writeobject(java.io.objectoutputstream s)
  throws java.io.ioexception{
// write out element count, and any hidden stuff
int expectedmodcount = modcount;
s.defaultwriteobject();
  // write out array length
  s.writeint(elementdata.length);
 // write out all elements in the proper order.
for (int i=0; i<size; i++)
   s.writeobject(elementdata[i]);
 if (modcount != expectedmodcount) {
   throw new concurrentmodificationexception();
 }
}

每次序列化的时候调用这个方法,先调用defaultwriteobject()方法序列化arraylist中的非transient元素,elementdata不去序列化它,然后遍历elementdata,只序列化那些有的元素,这样:

1、加快了序列化的速度

2、减小了序列化之后的文件大小

六、自己编写一个myarraylist

 

?
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package study.collection;
 
import java.util.arrays;
import java.util.collection;
import java.util.iterator;
import java.util.list;
import java.util.listiterator;
 
public class myarraylist implements list {
 
 //底层用一个数组接收
 private object[] elementdata;
 
 //用于记录集合的元素个数
 private int size;
 
 /**
  * 无参数构造,默认为大小10
  */
 public myarraylist()
 {
  this(10);
 }
 
 /**
  * 初始化带容量的构造方法
  * @param cap
  */
 public myarraylist(int cap)
 {
  super();
  if(cap < 0)
  {
   throw new illegalargumentexception("illegal cap: "+
     cap);
  }
  elementdata = new object[cap];
 }
 
 @override
 public boolean add(object e) {
  //1.添加之前确认集合中的大小是够,因此扩容判断
  ensurecapacity(size +1); //添加元素一个一个添加,因此size+1;
  //2.填充元素
  elementdata[size++] = e;
  return true;
 }
 
 /**
  * 扩容判断,因为只要添加元素,就需要判断容器的大小是否满足
  * @param i
  */
 private void ensurecapacity(int mincapacity) {
  //扩容前,需要获取当前的数组元素的大小
  int oldcapacity = elementdata.length;
  //只有当前的容量不满足,则扩容处理
  if(oldcapacity < mincapacity)
  {
   //新大小的比例,采用原来大小的1.5倍
   int newcapacity = (oldcapacity * 3)/2 + 1;
   //如果新算出来的大小不满足当前需要扩容的大小,则就以用户需要的为主,如果以满足则以算出来的最佳大小为主
   if(newcapacity < mincapacity)
   {
    newcapacity = mincapacity;
   }
   //比例算好后,开始执行数组的拷贝操作
   arrays.copyof(elementdata, newcapacity,object[].class);
  }
 }
 
 @override
 public void add(int index, object element) {
  //添加指定位置,首先需要做的就是确保索引满足要求,如果要添加的索引超过了元素个数中的大小
  if(index > size || index < 0)
  {
   throw new indexoutofboundsexception(
     "index: "+index+", size: "+size);
  }
  //如果没有超过,那么就需要开始添加元素,这个时候同样需要判断扩容
  ensurecapacity(size +1); //添加元素一个一个添加,因此size+1;
  //接着需要做的事情是需要将原来位于index 位置的元素,向后面移动
  //首先判断,index的后面是否还有元素
  int modnum = size - index;
  if(modnum > 0)
  {
   system.arraycopy(elementdata, index, elementdata, index+1, size - index);
  }
  //如果没有元素或者已经拷贝完成,则直接在对应的索引处放置元素即可
  elementdata[index] = element;
  //元素个数加+1
  size++;
 }
 
 @override
 public boolean addall(collection c) {
  //添加集合元素,首先需要将集合转换为数组,计算出数组的大小
  object[] a = c.toarray();
  //计算出需要的长度
  int numnew = a.length;
  //开始扩容判断
  ensurecapacity(size +numnew); //添加元素的个数为numnew
  //开始数组拷贝
  system.arraycopy(a, 0, elementdata, size, numnew);
  size += numnew;
  return numnew != 0;
 }
 
 @override
 public boolean addall(int index, collection c) {
  //首先索引的正确性
  if (index > size || index < 0)
   throw new indexoutofboundsexception(
   "index: " + index + ", size: " + size);
  //添加的元素集合转换为数组,计算要拷贝的长度,准备扩容
  object[] a = c.toarray();
  int numnew = a.length;
  ensurecapacity(size + numnew); // increments modcount
  //因为是指定位置扩容,因此需要判断下index后面是否有元素
  int nummoved = size - index;
  //如果大于0,说明要先空出位置来给a数组
  if(nummoved > 0)
  {
   system.arraycopy(elementdata, index, elementdata, index+1, size-index);
  }
  //空出为位置后,然后将集合的元素放到空出的位置上面
  system.arraycopy(a, 0, elementdata,index, numnew);
  size += numnew;
  return numnew != 0;
 }
 
 @override
 public void clear() {
  for (int i = 0; i < size; i++)
   elementdata[i] = null;
  size = 0;
 }
 
 @override
 public boolean contains(object o) {
  return indexof(o) >= 0;
 }
 
 @override
 public boolean containsall(collection c) {
  //迭代器暂不去实现
  return false;
 }
 
 @override
 public object get(int index) {
  //对于数组而言,根据索引获取元素非常简单,但需要先检查inde的合法性,避免越界
  rangecheck(index);
  return elementdata[index];
 }
 
 private void rangecheck(int index) {
  if (index >= size)
   throw new indexoutofboundsexception(
   "index: "+index+", size: "+size);
  }
 
 @override
 public int indexof(object o) {
  //循环遍历,找出元素,注意是equals比较
  if (o == null) {
   for (int i = 0; i < size; i++)
   if (elementdata[i]==null)
    return i;
  } else {
   for (int i = 0; i < size; i++)
   if (o.equals(elementdata[i]))
    return i;
  }
  return -1;
 }
 
 @override
 public boolean isempty() {
  return size == 0;
 }
 
 @override
 public iterator iterator() {
  //涉及迭代器,暂不去关注
  return null;
 }
 
 @override
 public int lastindexof(object o) {
  //反向获取,则反向循环
  if (o == null) {
   for (int i = size-1; i >= 0; i--)
   if (elementdata[i]==null)
    return i;
  } else {
   for (int i = size-1; i >= 0; i--)
   if (o.equals(elementdata[i]))
    return i;
  }
  return -1;
  
 }
 
 @override
 public listiterator listiterator() {
  //涉及迭代器,暂不去关注
  return null;
 }
 
 @override
 public listiterator listiterator(int index) {
  //涉及迭代器,暂不去关注
  return null;
 }
 
 @override
 public boolean remove(object o) {
  if (o == null) {
   for (int index = 0; index < size; index++)
    if (elementdata[index] == null) {
     fastremove(index);
     return true;
    }
  } else {
   for (int index = 0; index < size; index++)
    if (o.equals(elementdata[index])) {
     fastremove(index);
     return true;
    }
  }
  return false;
 }
 
 //找到指定的索引开始删除
 private void fastremove(int index) {
  int nummoved = size - index - 1;
  if (nummoved > 0)
   system.arraycopy(elementdata, index+1, elementdata, index,
        nummoved);
  elementdata[--size] = null;
  
 }
 
 @override
 public object remove(int index) {
  //合法性检查
  rangecheck(index);
  //取出原来老的元素,以便返回
  object oldvalue = elementdata[index];
  //需要开始拷贝数组,因为删除了索引处的元素,那么则需要向前移动元素
  //需要看后面有没有移动的元素,-1 是减去当前这个删除的元素
  int nummoved = size - index - 1;
  if (nummoved > 0)
   system.arraycopy(elementdata, index+1, elementdata, index,
      nummoved);//从index+1 开始拷贝到 index 处
  elementdata[--size] = null; //元素个数减去一,同事最后一个位置置空,等待垃圾回收
  
  return oldvalue;
 }
 
 @override
 public boolean removeall(collection c) {
  ////涉及迭代器,暂不去关注
  return false;
 }
 
 @override
 public boolean retainall(collection c) {
 ////涉及迭代器,暂不去关注
  return false;
 }
 
 @override
 public object set(int index, object element) {
  rangecheck(index);
 
  object oldvalue = elementdata[index];
  elementdata[index] = element;
  return oldvalue;
 }
 
 @override
 public int size() {
  return size;
 }
 
 @override
 public list sublist(int fromindex, int toindex) {
 ////涉及迭代器,暂不去关注
  return null;
 }
 
 @override
 public object[] toarray() {
   return arrays.copyof(elementdata, size);
 }
 
 @override
 public object[] toarray(object[] a) {
  if (a.length < size)
   // make a new array of a's runtime type, but my contents:
   return arrays.copyof(elementdata, size, a.getclass());
  system.arraycopy(elementdata, 0, a, 0, size);
  if (a.length > size)
   a[size] = null;
  return a;
 }
 
 //测试
 public static void main(string[] args)
 {
  myarraylist list = new myarraylist();
  list.add("333");
  list.add("444");
  list.add("5");
  list.add("344433");
  list.add("333");
  list.add("333");
  system.out.println(list.size());
//  system.out.println(list.get(6));
  list.remove("444");
  system.out.println(list.size());
 }
}

说明:其他关于jdk1.6 和 1.7 和 1.8 的区别可以看:

jdk1.8、jdk1.7、jdk1.6区别看这里

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/pony1223/p/7757836.html

延伸 · 阅读

精彩推荐