import java.util.Iterator;
import java.util.NoSuchElementException;

/**Realization of a set by means of an array, which is doubled
 *when the size of the set exceeds the capacity of the array
*/
public class ArraySet1<E> implements Set<E> {
	private E[] A; //array storing the elements of the set
	private int capacity=16; //initial length of array A
	private int size=0; //number of elements stored in the list
	
	
	
	/**Creates the list with initial capacity 16. */
	public ArraySet1(){
		A= (E[]) new Object[capacity];//Compiler may warn, but ok
	}
	
	
	
	
	
	public int size() {
       return size;
	}
	
	

	/**Adds the specified element to this set if not already present */
	public boolean add(E e) {
		boolean toAdd=false;
		if (!contains(e)){
			toAdd=true;
	        if(size==capacity){
		      capacity *=2;
		      E[] B=(E[]) new Object[capacity];
		      for (int i=0;i<size;i++)
			    B[i]=A[i];
		      A=B;
	        }
	        A[size]=e;
	        size++;
	    }
		return toAdd;
	}
	
	/**Removes all of the elements from this set*/
	public void clear(){
		for(int i=0;i<size();i++) A[i]=null;
		size=0;
	}
	
	/**Returns true if this collection contains the specified element*/
	public boolean contains(E e){
		for(E eTemp:this) if(eTemp.equals(e)) return true;
		return false;
	}
	
	
	
	
	
	/**Removes the specified element from this set, if it is present*/
	public boolean remove(E e){
		int i=0;
		boolean found=false;
		while((i<size()-1)&&(found==false)){
			if(A[i].equals(e)){
				A[i]=null;
				for(int j=i;j<size()-1;j++) A[j]=A[j+1];
				i=size()-1;
				size--;
			}
		}
		return found;
			
			
		
	}

	
	/**Returns true if the set contains no elements*/
	public boolean isEmpty() {
		return size==0;
	}
	
	
	
	public Iterator<E> iterator()
	{ArraySetIterator tempIterator=new ArraySetIterator();
	 return (Iterator<E>) tempIterator;}
	
	private class ArraySetIterator implements Iterator<E>{
		private int current=0;
		
		/**Returns true if the iteration has more elements*/
		public boolean hasNext()
		{return current<size();}
		
		public E next(){
			if(!hasNext())
				throw new NoSuchElementException();
			return A[current++];
		}
		
		/**Removes from the underlying collection the last element returned by the iterator*/
		public void remove(){};
			// not implemented
		}
		
	
	
	public String toString(){
		String s="";
		for(E sTemp:this) s+=" "+sTemp;
		return s;
		 }

}