Tuesday, October 27, 2009

CustomStack upgrades

My CustomStack now comes with several other new features. I can actually check if an Object exists in the Stack. Once the Object is found, a boolean true is returned. In addition to that, I've also added a method to retrieve an element with a given 0-based index number. I call it elementAt and it has a similar functionality of get. To the readers who are accustomed to the methods of a Stack, I have also added the method peek. Basically, it's a method to retrieve the element at the top of the Stack. The method search returns the 0-based index number of the first found element and -1 is returned if the element is not found. Here are the summary of methods of the newly improved CustomStack:
contains(Object input)
elementAt(int index)
peek()
search(Object input)

Below is the code snippet.

public boolean contains(Object input){
boolean found = false;
if(empty()){
throw new RuntimeException( "Stack is already empty. No elements to check." );
}
for(int i = 0; i<size(); i++) {
if (stackElements[i].hashCode() == input.hashCode()) {
found = true;
break;
}
}
return found;
}

public Object elementAt(int index){
return get(index);
}

public Object peek(){
return top();
}

public int search(Object input){
int index = -1;
if(empty()){
throw new RuntimeException( "Stack is already empty. No elements to search." );
}
for(int i = 0; i<size(); i++) {
if (stackElements[i].hashCode() == input.hashCode()) {
index = i;
break;
}
}
return index;
}

Click here to view the previous code of CustomStack.

0 comments:

Post a Comment