-
Notifications
You must be signed in to change notification settings - Fork 641
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #42 from CheungChanDevCoder/master
将ensureCapacity设为public方法 忽略bin文件夹
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
/bin | ||
/.settings | ||
.classpath | ||
.project |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
package list; | ||
|
||
import java.util.Arrays; | ||
|
||
public class ArrayList<E> { | ||
private transient static final int INITIAL_SIZE = 10; | ||
private transient int arrayLength; | ||
private transient int size; | ||
private transient E[] array; | ||
public ArrayList(){ | ||
array = (E[]) new Object[INITIAL_SIZE]; | ||
arrayLength = INITIAL_SIZE; | ||
} | ||
public ArrayList(int size){ | ||
if(size<=0){ | ||
throw new IllegalArgumentException("参数不可以小于0"); | ||
} | ||
array = (E[])new Object[size]; | ||
arrayLength = array.length; | ||
ensureCapacity(size); | ||
this.size = size; | ||
} | ||
public int size(){ | ||
return size; | ||
} | ||
public void add(E e){ | ||
ensureCapacity(size+1); | ||
array[size] = e; | ||
size++; | ||
} | ||
public E get(int index){ | ||
if(index<0 || index > size){ | ||
throw new IllegalArgumentException("索引越界"); | ||
} | ||
return array[index]; | ||
|
||
} | ||
public E set(int index, E e){ | ||
if(index<0 || index>size){ | ||
throw new IllegalArgumentException("索引越界"); | ||
} | ||
E result = array[index]; | ||
array[index] = e; | ||
return result; | ||
} | ||
public void ensureCapacity(int size){ | ||
E[] oldArray = array; | ||
int oldSize = arrayLength; | ||
while(size>arrayLength){ | ||
arrayLength = arrayLength + (arrayLength >> 1); | ||
} | ||
if(oldSize!=arrayLength){ | ||
array = Arrays.copyOf(oldArray, arrayLength); | ||
} | ||
} | ||
} |