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.
I always wanted to learn this stuff but never had time... thanks for sharing and keep it up!
ReplyDeleteThanks!
ReplyDeleteI think your blog is great. I'm studying programming soon.
ReplyDeletebest java blog .. Bdw check out my blog n lets follow each other
ReplyDeletechuchu-chulala.blogspot.com/