简体   繁体   中英

Call a method from another class without initialization in java

I'm a bit confused by the code below. From my understanding, private ListElement<E> head is just the same thing as saying int head . If this is true, then one cannot call a method from an outside class without initializing it, so head.setPrev() won't work before you say ListElment<E> head = new ListElment<>() . which contradicts the code below. I must have misunderstood something about java. Cloud someone points it out? Thanks in advance

public class DoublyLinkedList<E> {

private ListElement<E> head;
private ListElement<E> tail;



public DoublyLinkedList() {
    head = null;
    tail = null;
}

public void addToHead(E value) {
    ListElement<E> e = new ListElement<>(value);

    if (!isEmpty()) {
        e.setNext(head);
        head.setPrev(e);
    } else { // empty
        tail = e;
    }

    head = e;
}

You omitted the code for isEmpty() .

Assuming a reasonable implementation, then if isEmpty() returns false , then it is guaranteed that head is not null, because there has to be at least one element in the list if it's not empty.

head is a reference to a ListElement object. It starts out initialized to null . On the very first call to addToHead() the call to isEmpty() returns true , so the else branch of the if-then-else executes. The end result is that after that first call, both head and tail now refer to the element just created.

The "then" branch executes only if the list is not empty, in which case, by definition, head cannot be null.

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