NadaHombre wrote:
Hello,
If I want to make a class which is a stack of objects of some specific type
(not just "Objects"), what is the best way to do it?
I wonder if there is some generally accepted "best" way to do this, because
it must come up a lot.
I personally create a new class which mimics all the methods of
java.util.Stack , and keeps a java.util.Stack as a private instance
variable. The new class changes the return types of pop and peek and the
argument type of push. Is this the most elegant solution?
I'm a student programmer, and appreciate any insight.
Your approach is sound and common. Extending Stack is not the best
choice, because you cannot hide the public methods from Stack that
accept Objects so you cannot ensure that your internal stack is homogeneous.
Now, a couple of notes and suggestions, since you are a student.
1) Stack is an extension of Vector, which is a synchronized class.
Unless you have a specific need for synchronization in your application,
this is overhead you do not need. Instead use the LinkedList class as
the internal reference.
2) Does your implementation implement List? If not, that would be a
good improvement that would allow for future re-usability and
interoperability with other libraries. (Suggestion, if you are going to
implement List, the easier way is to extend AbstractList.)
3) Note that in Java 1.5 (coming soon), you will be able to have
so-called "generics", which are similar to C++ templates. This will
make the need for such implementations disappear.
Ray