package Stack;
import java.util.EmptyStackException;
public class Stack<ObjectType> {
private ObjectType[] stackArray; // Array elements put on the stack
private int stackSize; // amount of elements on the stack
private int topOfStack; // monitoring the element on the top of the stack
public Stack<ObjectType>(int stackSize) {
this.stackSize = stackSize;
this.stackArray = new Stack<ObjectType>[stackSize];
}
public void push(ObjectType input) throws ArrayIndexOutOfBoundsException {
if (topOfStack < stackSize) {
stackArray[topOfStack++] = input;
} else
throw new ArrayIndexOutOfBoundsException();
}
public ObjectType pop() {
if (topOfStack == 0)
throw new EmptyStackException();
ObjectType popped = stackArray[--topOfStack];
stackArray[topOfStack] = null;
return popped;
}
public ObjectType peek() {
if (topOfStack > 0)
return stackArray[topOfStack - 1];
else
return null;
}
public static void main(String[] args) {
String text = "Lorem ipsum dolor sit amet, dolore reformidans vel no, quo inermis deseruisse persequeris an. Qui ad veritus docendi. Suas feugiat commune sed te, odio docendi luptatum duo no.";
String[] txt = text.split("\\s|\\,\\s|\\.\\s|\\.");
Stack stack = new Stack(txt.length);
try {
for (int i = 0; i < txt.length; i++)
stack.push(txt[i]);
// stack.push("One more plox");
} catch (ArrayIndexOutOfBoundsException stackFull) {
System.out
.println("With all the respect, Sir, but stack is already full.");
}
stack.pop();
System.out.println(stack.peek());
}
}
Problem jest taki, że chciałbym stworzyć uniwersalny stos dla dowolnego obiektu, ale niestety jak widać nie jest to takie proste jak myślałem. Znalazłem takie coś na stackoverflow http://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java, ale nie mam pojęcia jaka jest różnica pomiędzy podanymi rozwiązaniami, a tym bardziej nie wiem które jest bardziej poprawne, a nie chcę korzystać z czegoś czego nie rozumiem.. I czy wgl się z czegoś takiego korzysta? Czy jest sens to obchodzić na siłe, czy może jakoś inaczej warto to zrobić??
Oczywiście jeżeli macie dodatkowo jakieś uwagi na temat mojego kodu, coś jest brzydko, niepoprawnie, albo tak się nie robi to dajcie znać.