Thursday, 15 September 2011

Java: The Stack Object & Class

    Continuing from yesterday's post, we need to group all this stuff together, all the methods and variables into 1 unit (the object). This still isn't enough if we need more than 1 stack, how would we separate data between them? Well, we'd need to create a second object. This can be annoying to do, especially if a large number of stacks is required, or the data within the object becomes too cumbersome. So what now? We should probably work with some kind of template! Make everything easier, make everything faster, good times. And that's exactly what a class amounts to. A template.

    So let's look at an outline for a template for stacks, based on yesterday's quick specifications!
    This is very rudimentary, as you can see, but it provides an outline for the class quite nicely. We see what functions still need to be worked on (At this point, all of 'em). Within this class body (each class should ideally be it's own file, due to object oriented yadda yadda), we have the class scope. Public methods and variables can be accessed from outside this scope, such as a case where the class is used as a cog in a larger machine of a program, while private denotes....privacy. Only this class may use the methods and alter variables flagged as such. This is surprisingly useful, when you want to use helper functions to perform a various amount of smaller tasks as part of a larger function, keeping only the umbrella function public. Stuff like that.

    This looks alright, I hope? Well, it isn't, but you should understand what's going on in the actual code at this point. HOWEVER. What happens if we try to look at the top value when there isn't one there? (Hint, the compiler hates you and throws errors at you). Another, seemingly less important task to take care of is the line:

    int size = stack.size();

....which we not only use twice, but never actually use the result, and instead need to subtract from it each time. An easier way to do this is create a helper method, something like, getLastIndex(), but easier to type out. This method would ideally run the above line, then return that value minus 1. This could save time, making both functions that use it 1 line long:

    public void pop() {
        stack.remove( stack.getLast() );

    So let's see if you can create the helper function, and find some way to deal with the potential breaking that happens when you try to pop/top an empty stack. I'll post a quick solution next time and  that's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us.