小型ArrayListの実現
2186 ワード
class MyArrayList<T>{
private Object [] elements=new Object [10];
private int addition;
{addition=10;}
public MyArrayList(){
}
public MyArrayList(int size){
this.setElements(new Object[size]);
}
public Object[] getElements() {
return elements;
}
public void setElements(Object[] elements) {
this.elements = elements;
}
private void extendCapacity(){
int currentSize=this.getElements().length;
int expectSize=currentSize+addition;
Object[] newElements=new Object[expectSize];
System.arraycopy(this.getElements(), 0, newElements, 0, currentSize);
this.setElements(newElements);
newElements=null;
}
private boolean isFull(){
for(Object obj:this.getElements()){
if(obj==null){
return false;
}
}
return true;
}
private int capacity(){
return this.getElements().length;
}
public void add(T element){
if(this.isFull()){
this.extendCapacity();
}
for(int i=0;i<this.capacity();i++){
Object obj=this.getElements()[i];
if(obj==null){
this.getElements()[i]=element;
break;
}
}
}
public int size(){
int count=0;
for(int i=0;i<this.capacity();i++){
if(this.getElements()[i]!=null){
count++;
}
}
return count;
}
@Override
public String toString() {
String str="[";
for(int i=0;i<this.capacity();i++){
Object obj=this.getElements()[i];
if(obj!=null){
str+=obj.toString();
str+=",";
}
}
str=str.substring(0, str.length()-1);
str+="]";
return str;
}
public void addAll(MyArrayList<T> list){
}
public class MyIterator implements Iterator<T>{
private int index=-1;
private MyArrayList<T> outer=MyArrayList.this;
@Override
public boolean hasNext() {
while(index<outer.capacity()-1){
index++;
if(outer.getElements()[index]!=null){
return true;
}
}
return false;
}
@Override
public T next() {
return (T) outer.getElements()[index];
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
public MyIterator iterator(){
return new MyIterator();
}
}