Skip to content

Commit 4c3bb7a

Browse files
committed
添加SimpleArrayList的get方法
1 parent d07bbe3 commit 4c3bb7a

File tree

3 files changed

+100
-29
lines changed

3 files changed

+100
-29
lines changed

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

Lines changed: 0 additions & 29 deletions
This file was deleted.
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package cn.byhieg.collectiontutorial.listtutorial;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Created by byhieg on 17/2/7.
7+
* Mail to byhieg@gmail.com
8+
*/
9+
public class SimpleArrayList<E> {
10+
11+
12+
private final static int DEFAULT_CAPACITY = 10;
13+
private int size = 0;
14+
15+
private Object [] elementData;
16+
17+
public SimpleArrayList(){
18+
this(DEFAULT_CAPACITY);
19+
}
20+
21+
22+
public SimpleArrayList(int size){
23+
if (size < 0){
24+
throw new IllegalArgumentException("默认的大小" + size);
25+
}else{
26+
elementData = new Object[size];
27+
}
28+
}
29+
30+
31+
public void add(E e){
32+
isCapacityEnough(size + 1);
33+
elementData[size++] = e;
34+
}
35+
36+
public void add(int index, E e) {
37+
checkRangeForAdd(index);
38+
isCapacityEnough(size + 1);
39+
System.arraycopy(elementData,index,elementData,index + 1,size - index);
40+
elementData[index] = e;
41+
size++;
42+
}
43+
44+
private void isCapacityEnough(int size){
45+
if (size > DEFAULT_CAPACITY){
46+
explicitCapacity(size);
47+
}
48+
if (size < 0){
49+
throw new OutOfMemoryError();
50+
}
51+
}
52+
private final static int MAX_ARRAY_LENGTH = Integer.MAX_VALUE - 8;
53+
54+
private void explicitCapacity(int capacity){
55+
int newLength = elementData.length * 2;
56+
if (newLength - capacity < 0){
57+
newLength = capacity;
58+
}
59+
if (newLength > (MAX_ARRAY_LENGTH)){
60+
newLength = (capacity > MAX_ARRAY_LENGTH ? Integer.MAX_VALUE : MAX_ARRAY_LENGTH);
61+
}
62+
elementData = Arrays.copyOf(elementData, newLength);
63+
}
64+
65+
private void checkRangeForAdd(int index){
66+
if (index < 0 || index > size){
67+
throw new IndexOutOfBoundsException("指定的index超过界限");
68+
}
69+
}
70+
71+
public E get(int index){
72+
73+
}
74+
75+
76+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package cn.byhieg.collectiontutorialtest;
2+
3+
import cn.byhieg.collectiontutorial.listtutorial.SimpleArrayList;
4+
import junit.framework.TestCase;
5+
6+
import java.util.ArrayList;
7+
8+
/**
9+
* Created by byhieg on 17/2/7.
10+
* Mail to byhieg@gmail.com
11+
*/
12+
public class SimpleArrayListTest extends TestCase {
13+
public void testAdd() throws Exception {
14+
SimpleArrayList<Integer> list = new SimpleArrayList<>();
15+
for (int i = 0 ; i < 20 ; i++){
16+
list.add(i);
17+
}
18+
19+
list.add(5,15);
20+
21+
System.out.println("aaa");
22+
}
23+
24+
}

0 commit comments

Comments
 (0)