Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

whats the difference between poll() and pop() for linkedlist in java? [duplicate]

I recently found there are two similar methods for linkedlist in java API, they all delete the first node and return it. I wrote the following codes to test and they did exactly same thing.Do they really work exactly same?

    test.add(1);
    test.add(2);
    test.add(3);
    System.out.println(test.pop());
    for(int i = 0; i < test.size();i++ ){
        System.out.print(test.get(i) + " ");
    }
    System.out.println("");
    System.out.println(test.poll());
    for(int i = 0; i < test.size();i++ ){
        System.out.print(test.get(i) + " ");
    }
    System.out.println("");

Thanks!!!

like image 520
Mingyaaa Avatar asked Feb 22 '16 06:02

Mingyaaa


2 Answers

They're functionally equivalent (save for how they handle the empty-list case), but you get both variants because LinkedList is an implementation of both a queue and a stack (namely Queue and Deque).

You can see their implementations in the source code:

public E poll() {
    final Node<E> f = first;
    return (f == null) ? null : unlinkFirst(f);
}

public E pop() {
    return removeFirst();
}

public E removeFirst() {
    final Node<E> f = first;
    if (f == null)
        throw new NoSuchElementException();
    return unlinkFirst(f);
}

So poll() returns null if the list is empty, and pop() (and removeFirst()) raises a NoSuchElementException. This makes pop() a slightly nicer method to use, since you don't have to deal with nulls.

like image 159
dimo414 Avatar answered Nov 15 '22 17:11

dimo414


Returning null + removing operations: poll() docs

Throwing exception + removing operations: pop()docs

like image 34
Michal Frystacky Avatar answered Nov 15 '22 18:11

Michal Frystacky