What's the difference between the static class and class?


  • 0
    R
    class MinStack {
    Stack<Elem> stack = new Stack<MinStack.Elem>();
    
    public void push(int x) {
        if(stack.isEmpty() || x < stack.peek().min){
        	stack.push(new Elem(x, x));
        }else{
        	stack.push(new Elem(stack.peek().min, x));
        }
    }
    
    public void pop() {
        stack.pop();
    }
    
    public int top() {
        return stack.peek().val;
    }
    
    public int getMin() {
        return stack.peek().min;
    }
    
    public class Elem{
    	int min;
    	int val;
    	
    	public Elem(int min,int val) {
    		this.min = min;
    		this.val = val;
    	}
    }
    

    }

    enter image description here

    I tried to solve this question by using the above codes at the first time.But it would show memory limit exceeded...

    (img might be understood what I say easier……)

    And then I think of using static class,and I get it done...But now I'm confused by it.I search lots of Blog to read,and Debug the codes,finally I find that,the object of MinStack,such as minStack..

    The object of Elem inside minStack.stack contains "this", and "this" leads to the minStack,which occurs the memory limit exceeded.

    So now,I'am thinking the reason causing this.


  • 0
    G

    Normal internal class contains a reference to the outside class, but static internal class doesn't have a reference to the outside class.

    Since you are using eclipse, you can easily test it.
    enter image description here

    enter image description here


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.