PDA

View Full Version : Creating Stacks


Touchstone57
03-03-2009, 06:33 PM
Sorry, asking for help, again! I'm still fairly new with this programming lark.

Basically I'm trying to create a Stack in my PublicLibrary class, but having difficulty getting it working. So far, I can only use the stack created in the PublicLibrary in my main method which is TestLibraries.

public class PublicLibrary {

public Stack<LibraryItem> PublicLibraryStack = new Stack<LibraryItem>();


}

My thoughts here would be to for the next line to be

PublicLibraryStack.<INVOKE OPERATION>

But no operations are given available. The only way I can manipulate my stack is in my main method, using this code, in my other class.

PublicLibrary pl = new PublicLibrary()
pl.PublicLibraryStack.<WHATEVER OPERATION> //eg. add()

So how can I get one created inside my PublicLibrary class? Any help would be greatly appreciated, thanks.

Fou-Lu
03-03-2009, 07:59 PM
This is the behaviour of OO programming languages. You can't add to it within you're member declarations, you have to do it in a method. What you can do is use the OO member instead of accessing it via another property from an object context (using this.).
This is probably what I'd do:

public class PublicLibrary implements Collection<LibraryItem>
{
private Collection<LibraryItem> obLibraryCollection;

public PublicLibrary(Collection<LibraryItem> obLibraryCollection)
{
this.obLibraryCollection = obLibraryCollection;
}
public boolean add(LibraryItem a)
{
return this.obLibraryCollection.add(a);
}
// ... chain all of the collection items to the library collection.
}

Here's the advantage to this approach.

public static void main(String[] argv)
{
PublicLibrary plVector = new PublicLibrary(new Vector<LibraryItem>());
plVector.add(new LibraryItem()); // Whatever in here

PublicLibrary plLL = new PublicLibrary(new LinkedList<LibraryItem>());
plLL.add(new LibraryItem());
}

As you can see, you've now eliminated the dependancy on the collection type. This is the power of interfaces, all we care about is we're getting a collection, which all of these are (see them here: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html, you can use any of the classes from the all known classes section, or create you're own). You'll also notice that a PublicLibrary could theoretically contain another PublicLibray. It would work (all the methods should be chained to the same calls from the provided obLibraryCollection), though it does seem a little silly.