简体   繁体   中英

Stacks in Java, why does it use an if?

Below is the code for a Stack program. My question specifically is about the push method, where at the beginning, it checks if (pContent != null). Why does it do that? I commented the if statement out and it still worked fine, so whats the reason for the usage of it. Also , what is the difference between pContent and ContentType here?

Im trying to understand this code I got, Im very thankful for any help.

import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)




public class Stacko<ContentType> extends Actor {

  /* --------- Anfang der privaten inneren Klasse -------------- */

  private class StackNode {

    private ContentType content = null;
    private StackNode nextNode = null;

    public StackNode(ContentType pContent) {
      content = pContent;
      nextNode = null;
    }

    public void setNext(StackNode pNext) {
      nextNode = pNext;
    }

    public StackNode getNext() {
      return nextNode;
    }

    public ContentType getContent() {
      return content;
    }
  }

  /* ----------- Ende der privaten inneren Klasse -------------- */

  private StackNode head;

  public void Stack() {
    head = null;
  }

  public boolean isEmpty() {
    return (head == null);
  }

  public void push(ContentType pContent) {
    if (pContent != null) {
      StackNode node = new StackNode(pContent);
      node.setNext(head);
      head = node;
    }
  }

  public void pop() {
    if (!isEmpty()) {
      head = head.getNext();
    }
  }

  public ContentType top() {
    if (!this.isEmpty()) {
      return head.getContent();
    } else {
      return null;
    }
  }
}

There is a possibility that it is null (=undefined). This happens when you tell it "Put nothing in there". The program is not able to add "nothing" and throws an error.

So one should check whether it is null first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM