Generics question

  • Thread starter Thread starter Mike P
  • Start date Start date
M

Mike P

I am reading through the basics of generics from several different
sources, and one of the things that is common amongst all of them seems
to be the example of type-safe stack and converting it to be able to use
generics. However, I am not familiar with this and I'm unsure what
exactly the Push and Pop methods are used for, and none of the examples
explain this. Could someone explain it to me?
 
Hi,

Not too sure what level you're coming at this from, so If I've
oversimplified my apologies.

A stack is a bit like an array, but you can only get at the "first"
element - the top of the stack.

For example, If I push these strings on to a stack : "one", "two", "three",
"four" the stack looks like this :

"four" <--- top of the stack
"three"
"two"
"one"

If I now perform a Pop on the stack I get "four" back and the stack looks
like this :

"three" <---- top of the stack
"two"
"one"

If I then push "five" on to the stack it looks like this :

"five" <---- top of the stack
"three"
"two"
"one"

And "five" is what you get if you perform a pop. So you'd use a stack to
queue up objects when it was important to always get the most recently
queued object. They can also be called a LIFO queue - Last In First Out.

HTH,

Adam
==========
 
To be honest, I'm not sure that a stack is the best example of
generics - a list (List<T>) would be simpler to understand.

However, to answer your question: a stack is a "first in, last out"
store (imagine the spike that you sometimes see on restaurant counters
with food tickets on). "Push" places an item onto the stack spike;
"Pop" takes the *most recent* item back off the spike and returns
it...
so:
[stack: empty]
push "1"
[stack: 1]
push "2"
[stack: 1, 2]
pop: returns 2
[stack: 1]
pop: returns 1
[stack: empty]

Marc
 
Back
Top