/**
* this is my ArrayList
* @param <Object>
*/
public class myarraylist<Object> implements Iterable<Object> {
private static final int DEFAULT_CAPACITY = 10; //用来定义默认数组的长度
private int thesize; //用来控制theitems数组的长度(实际也就是控制myarrarlist的长度)
private Object[] theitems; //用object类型来实现一个数组(实际也就是myarraylist)
public int getThesize() {
return thesize;
}
public void setThesize(int thesize) {
this.thesize = thesize;
}
public myarraylist(){
clear();
}
public void clear(){
thesize = 0;
ensureCapacity(DEFAULT_CAPACITY);
}
public boolean isEmpty(){
return size()==0;
}
/**
* 传入一个下标获取对应的值
* @param index
* @return
*/
public Object get(int index){
if(index<0 || index >=size()){
throw new IndexOutOfBoundsException();
}
return theitems[index];
}
public boolean add(Object x){
add(x,size());
return true;
}
public void trimtosize(){
ensureCapacity(size());
}
public void add(Object x,int index){
if(size() == theitems.length){
ensureCapacity(size()*2+1);
}
theitems[index] = x;
thesize++;
}
public Object remove(int index){
Object removeitem = get(index);
for(int i=index;i<size();i++){
theitems[i] = theitems[i+1];
}
thesize--;
return removeitem;
}
private void ensureCapacity(int newCapacity) {
Object[] old = theitems;
theitems = (Object[]) new java.lang.Object[newCapacity];
if(newCapacity < thesize){
for(int i=0;i<newCapacity;i++){
theitems[i] = old[i];
}
}
for(int i=0;i<size();i++){
theitems[i] = old[i];
}
}
private int size() {
return thesize;
}
public Iterator<Object> iterator(){
return new ArrayListIterator();
}
@Override
public void forEach(Consumer<? super Object> action) {
}
@Override
public Spliterator<Object> spliterator() {
return null;
}
public class ArrayListIterator implements Iterator<Object> {
private int current = 0;
@Override
public boolean hasNext() {
return current<size();
}
@Override
public Object next() {
if(!hasNext()){
throw new IndexOutOfBoundsException();
}
return theitems[current++];
}
@Override
public void remove() {
myarraylist.this.remove(--current);
}
}
}
用数组的方式实现ArrayList
最新推荐文章于 2021-10-27 21:30:11 发布