posted 12 years ago
Hi Jerry, here are a few things to consider.
- Your class is not generic. It would be far more useful if you parameterized it, so your client can push and pop objects of a specific type.
- Why should it be illegal to add null elements to a stack?
- Your Stack(Object, Object[]) constructor is incredibly inefficient. You are creating a new array for every element in the given object array, and copying all the elements. Why not just create the new array in one go?
- If the array argument contains null elements and you want to disallow them (again, I don't understand why), you can just throw an exception upon discovery of the first null element.
- Even if you don't want to throw an exception, you can just count the number of null objects in the given array first, and then still create the new array in one go.
- Why are the semantics of the Stack(Object[]) constructor so different from the former?
- Your isEmpty() method uses a lot of redundant code. Just return size == 0, or Campbell will eat you.
- I'm all for clarity and using lots of variables and all, but why not just have your top() method return elements[size -1]?
- Don't use StringBuffer, use StringBuilder.
Now I know this is an exercise, but consider how useful such a class would be. It would probably only be useful for defensive copying if you want to return a stack field from a method in another class, in which case you might as well return Collections.unmodifiableCollection(myStack), where myStack is an instance of the Deque interface. It's also very inefficient, because it achieves its immutability through lots of copying. To make it more efficient, you could consider letting all the instances that are derived from the same stack (through push and pop operations) share the same array. They can just keep some index fields around to tell them which part of the array is valid for them.