Salve ragazzi!!!
Sto cercando di creare due classi che simulino il funzionamento di code e liste. Sono classi semplici, non parametriche, che usano soltanto un array di tipo Object. La sfida è proprio in questo .
Eccole qui. Vi chiedo: voi come le migliorereste? Partendo dal presupposto che non voglio usare ArrayList ma solo array veri e propri di tipo Object[].
codice:
/**
 * A class equals to Stack class of java, but this is not a parametric class;
 * indeed, it uses an Object[] array.
 * Methods, otherwise, are the same and with the same functionalities.
 * 
 * @author Simone
 *
 */
public class MyArrayStack
{
	public MyArrayStack(int aSize)
	{
		arraySize = aSize;
		object = new Object[arraySize];
		position = - 1;
	}
	
	public void push(Object element)
	{
		isFull();
		
		object[++position] = element;
	}
	
	public Object pop()
	{
		if (isEmpty())
			throw new IllegalStateException();
		return object[position--];
	}
	
	public Object peek()
	{
		if (isEmpty())
			throw new IllegalStateException();
		return object[position];
	}
	
	public boolean isEmpty()
	{
		return position < 0;
	}
	
	private void isFull()
	{
		if (position >= arraySize - 1)
		{
			Object[] newObject = new Object[object.length * 2];
			System.arraycopy(object, 0, newObject, 0, object.length);
			object = newObject;
		}	
	}
	
	private Object[] object;	
	private int arraySize;
	private int position;
}
codice:
import java.util.NoSuchElementException;

/**
 * A class to simulate a circular queue
 * @author Simone
 *
 */
public class MyCircularArrayQueue
{
	public MyCircularArrayQueue(int capacity)
	{
		theSize = capacity;
		elements = new Object[theSize];
		head = -1;
		tail = -1;
	}
	
	/**
	 * Add an object at the end of queue
	 * @param element
	 */
	public void add(Object element)
	{
		isFull();
		
		elements[++tail] = element;
	}
	
	/**
	 * Remove first element in queue
	 * @return
	 */
	public Object remove()
	{
		if (tail < 0)
			throw new NoSuchElementException();
		return elements[++head];
	}
	
	/**
	 * return size of queue
	 */
	public int size()
	{
		return elements.length;
	}
	
	/**
	 * Check if array is full; if it is the case, creates a new array.
	 */
	private void isFull()
	{
		if (tail >= theSize - 1)
		{
			Object[] newElements = new Object[elements.length * 2];
			for (int i = 0; i < elements.length; i++)
			{				
					System.arraycopy(elements, head + 1 +i, newElements, i, 1);
			}
			
			elements = newElements;
		}
	}
	
	private int head;
	private int tail;
	private int theSize;
	private Object[] elements;
}
Grazie mille a tutti coloro che vorranno dedicarci qualche minuto