Sunday, 18 September 2011

Java: Generic Classes

    Okay, so now we have our integer stack. Well, apart from the parameter for push, and the return value for top, what's limiting it to integers? (Hint: Nothing) The code itself works pretty independently of data types, other than that, so. Hey, remember ArrayLists? The container classes we had that specified a type on initialization with the angle brackets? Recalling that apart from not allowing primitive types, it worked great. So how do we do that for our stack?

    In the class declaration, we want to place some variable name. Lets use T.

public class Stack<T> { ..


   Then, every item placed into this stack is just an object of type T, which isn't an actual thing. Now we also need to replace every instance of int when referring to element types with T, like so (Do not replace the int for last, as that's looking for the index of the last item as opposed to doing something with the elements of the stack!):

    See? It's easy. Every item in the ArrayList we're utilizing is now just a generic "T" Object. Not specifically integers, or strings. In fact, you can try pushing an int and a String onto the same stack and it'll accept them both just fine. However, if you want a generic class, but to use it for a specific type based on where you're using that class, be sure to specify what you want the type to be! So if we wanted this generic stack to only be for Integers:

GenericStack<Integer> intStack = new GenericStack();


    And now you can't push any Strings or what have you onto it.


No post tomorrow, and that's it for tonight. Comment, follow, subscribe, share etc, and see you on Monday!


    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. 

5 comments:

  1. I always wanted to learn this stuff but never had time... thanks for sharing and keep it up!

    ReplyDelete
  2. I think your blog is great. I'm studying programming soon.

    ReplyDelete
  3. best java blog .. Bdw check out my blog n lets follow each other

    chuchu-chulala.blogspot.com/

    ReplyDelete