Skip to content

Commit aaf06bd

Browse files
committed
完成SimpleArrayList
1 parent 4c3bb7a commit aaf06bd

2 files changed

Lines changed: 63 additions & 5 deletions

File tree

src/main/java/cn/byhieg/collectiontutorial/listtutorial/SimpleArrayList.java

Lines changed: 59 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
package cn.byhieg.collectiontutorial.listtutorial;
22

3+
import java.io.Serializable;
4+
import java.lang.annotation.ElementType;
35
import java.util.Arrays;
6+
import java.util.RandomAccess;
47

58
/**
69
* Created by byhieg on 17/2/7.
710
* Mail to byhieg@gmail.com
811
*/
9-
public class SimpleArrayList<E> {
12+
public class SimpleArrayList<E> implements RandomAccess,Cloneable,Serializable{
1013

1114

1215
private final static int DEFAULT_CAPACITY = 10;
@@ -68,9 +71,63 @@ private void checkRangeForAdd(int index){
6871
}
6972
}
7073

74+
private void checkRange(int index) {
75+
if (index >= size || index < 0){
76+
throw new IndexOutOfBoundsException("指定的index超过界限");
77+
}
78+
}
7179
public E get(int index){
80+
checkRange(index);
81+
return (E)elementData[index];
82+
}
83+
84+
public int indexOf(Object o){
85+
if (o != null) {
86+
for (int i = 0 ; i < size ; i++){
87+
if (elementData[i].equals(0)){
88+
return i;
89+
}
90+
}
91+
}else {
92+
for (int i = 0 ; i < size ; i++){
93+
if (elementData[i] == null) {
94+
return i;
95+
}
96+
}
97+
}
98+
99+
return -1;
100+
}
101+
102+
public boolean contains(Object o){
103+
return indexOf(o) >= 0;
104+
}
105+
106+
public int size(){
107+
return size;
108+
}
72109

110+
public boolean isEmpty(){
111+
return size() == 0;
73112
}
74113

75-
114+
115+
public E remove(int index) {
116+
E value = get(index);
117+
int moveSize = size - index - 1;
118+
if (moveSize > 0){
119+
System.arraycopy(elementData,index + 1, elementData,index,size - index - 1);
120+
}
121+
elementData[--size] = null;
122+
return value;
123+
}
124+
125+
public boolean remove(Object o){
126+
if (contains(o)){
127+
remove(indexOf(o));
128+
return true;
129+
}else {
130+
return false;
131+
}
132+
}
76133
}

src/test/java/cn/byhieg/collectiontutorialtest/SimpleArrayListTest.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,10 @@ public void testAdd() throws Exception {
1616
list.add(i);
1717
}
1818

19-
list.add(5,15);
20-
21-
System.out.println("aaa");
19+
list.remove(1);
20+
for (int i = 0 ; i < list.size(); i++) {
21+
System.out.println(list.get(i));
22+
}
2223
}
2324

2425
}

0 commit comments

Comments
 (0)