streamc
streamc

Reputation: 698

object stack Albahari

Here is example of Albahari

public class Stack
{
int position;
object[] data = new object[10]; // Why 10 nor 1? 
public void Push (object obj) { data[position++] = obj; } //do not understood; Why there is no loop
public object Pop() { return data[--position]; } //do not understood Why there is no loop
}

Stack stack = new Stack();
stack.Push ("sausage");
string s = (string) stack.Pop(); // Downcast, so explicit cast is needed
Console.WriteLine (s); // sausage

I rewrote code as listened here

public class Stack
{

    object[] data = new object[1];
    public void Push(object obj) { data[0] = obj; }
    public object Pop() { return data[0]; }
}

        Stack stack = new Stack();
        stack.Push("abigale ff");
        string s = (string)stack.Pop(); 
        Console.WriteLine(s); // abigale ff

Why there is 10 in new object[10]; instead of 1 or 100 Why were used increment in data position? I do not understand how data position works.

{ data[position++] = obj; } and { return data[--position]; } How it works without loops? I try to push 2 values before pop and write it before pop but it shows me only second value

Upvotes: 0

Views: 115

Answers (1)

TheGeneral
TheGeneral

Reputation: 81513

Disregarding all the problems with this stack class, your refactoring obviously broke it. As alluded to by the comments, the key information you are lacking is actually what the ++ and -- operator does, which seemingly led you to believe the position field was redundant.

++ Operator (C# Reference)

The increment operator (++) increments its operand by 1. The increment operator can appear before or after its operand: ++variable and variable++.

Remarks

The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.

The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented

public class Stack
{
    int position;
    object[] data = new object[10]; // Why 10 nor 1? 
    public void Push (object obj) { data[position++] = obj; }
    public object Pop() { return data[--position]; }
}

For example

When you call Push it gets the value out of the data array at position then increments position

When you call Pop it decrements position then gets the value out of the data array at position


There is also a nice little example on the increment page, that shows you how it works

class MainClass
{
    static void Main()
    {
        double x;
        x = 1.5;
        Console.WriteLine(++x);
        x = 1.5;
        Console.WriteLine(x++);
        Console.WriteLine(x);
    }
}

Output

2.5
1.5
2.5
*/

Upvotes: 5

Related Questions