linkedlist vs arraylist- an in depth look at java.util.linkedlist

of 84 /84
2015, Marcus Biel, http://www.marcus-biel.com/ java.util.Link edList Marcus Biel, Software Craftsman http://www.marcus-biel.com

Author: marcus-biel

Post on 15-Jan-2017

425 views

Category:

Education


1 download

Embed Size (px)

TRANSCRIPT

java.util.LinkedList

java.util.LinkedListMarcus Biel, Software Craftsmanhttp://www.marcus-biel.com

2015, Marcus Biel, http://www.marcus-biel.com/

Explore the Linked List data structure further, specifically focusing on the java.util.LinkedList class for more visit-

Doubly Linked List233

17

9

42

In the previous episode I introduced you to the Linked List data structure.

2015, Marcus Biel, http://www.marcus-biel.com/

In the previous ( http://www.slideshare.net/MarcusBiel/linked-listdata-structure ) episode I introduced you to the Linked List data structure.

Doubly Linked List233

17

9

42

As the name implies, the Java class LinkedList is called LinkedList because internally it is based on a Doubly Linked List.

2015, Marcus Biel, http://www.marcus-biel.com/

As the name implies, the Java class LinkedList is called LinkedList because internally it is based on a Doubly Linked List.

Concept vs. ImplementationSo what is the difference between the LinkedList data structure and the class java.util.LinkedList?

2015, Marcus Biel, http://www.marcus-biel.com/

So what is the difference between the LinkedList data structure and the class java.util.LinkedList?

Concept vs. ImplementationAs an analogy, think of the abstract concept of a car and a concrete car.

2015, Marcus Biel, http://www.marcus-biel.com/

As an analogy, think of the abstract concept of a car and a concrete car.

Concept vs. ImplementationThe Linked List data structure is an abstract concept, independent of any specific programming language.

2015, Marcus Biel, http://www.marcus-biel.com/

The Linked List data structure is an abstract concept, independent of any specific programming language.

Concept vs. ImplementationThe LinkedList Java class is a concrete implementation of this abstract concept.

2015, Marcus Biel, http://www.marcus-biel.com/

The LinkedList Java class is a concrete implementation of this abstract concept.

java.util.LinkedList

ImplementsExtendsLinkedListSo in this tutorial, I will focus on one specific Linked List implementation, the java.util.LinkedList class.

2015, Marcus Biel, http://www.marcus-biel.com/

So in this episode I will focus on one specific Linked List implementation, the java.util.LinkedList class.

java.util.LinkedList

ImplementsExtends

List

LinkedListAmong other interfaces, LinkedList implements the java.util.List interface.

2015, Marcus Biel, http://www.marcus-biel.com/

Among other interfaces, LinkedList implements the java.util.List interface.

java.util.LinkedList

ImplementsExtends

List

LinkedListYou can have duplicate elements in a List and you can go from element to element in the same order as the elements were inserted.

2015, Marcus Biel, http://www.marcus-biel.com/

You can have duplicate elements in a List and you can go from element to element in the same order as the elements were inserted.

ArrayList vs. LinkedList

ImplementsExtends

ListArrayList

LinkedList

In a previous tutorial, I introduced you to the java.util.ArrayList class.

2015, Marcus Biel, http://www.marcus-biel.com/

In a previous tutorial (http://www.marcus-biel.com/arraylist/), I introduced you to the java.util.ArrayList class.

ArrayList vs. LinkedList

ImplementsExtends

ListArrayList

LinkedList

As you can see, both classes implement the List interface, which makes them somewhat similar. So whats the difference between ArrayList and LinkedList?

2015, Marcus Biel, http://www.marcus-biel.com/

As you can see, both classes implement the List interface which makes them somewhat similar. So whats the difference between ArrayList and LinkedList?

0123423317942

ArrayList vs. LinkedListFirst of all, ArrayList is based on an Array data structure,

2015, Marcus Biel, http://www.marcus-biel.com/

First of all, ArrayList ( http://www.marcus-biel.com/arraylist/ ) is based on an Array data structure,

0123423317942

233

17

9

42

ArrayList vs. LinkedListwhile LinkedList is based on a Doubly Linked List data structure.

2015, Marcus Biel, http://www.marcus-biel.com/

while LinkedList is based on a Doubly Linked List data structure.

0123423317942

233

17

9

42

ArrayList vs. LinkedListCompared to an ArrayList, the Doubly Liked List data structure of the LinkedList class allows more efficient insertion and removal of elements at any position within the List.

2015, Marcus Biel, http://www.marcus-biel.com/

Compared to an ArrayList, the Doubly Liked List data structure of the LinkedList class allows more efficient insertion and removal of elements at any position within the List.

ArrayList vs. LinkedList233

17

9

42

Therefore, as an implementation of the List interface prefer LinkedList over ArrayList if your main use is to add or remove elements at random positions in the List.

2015, Marcus Biel, http://www.marcus-biel.com/

Therefore, as an implementation of the List interface prefer LinkedList over ArrayList if your main use is to add or remove elements at random positions in the List.

ArrayList vs. LinkedList0123423317942

Otherwise, ArrayList might be a better choice, because storing elements in an array consumes less memory and generally gives faster access times.

2015, Marcus Biel, http://www.marcus-biel.com/

Otherwise, ArrayList might be a better choice, because storing elements in an array consumes less memory and generally gives faster access times.

ArrayList vs. LinkedList

ImplementsExtends

Collection

List

QueueLinkedList

Deque

ArrayList

Besides the different data structures of ArrayList and LinkedList LinkedList also implements the Queue and the Deque interfaces which gives it some additional functionality over ArrayList.

2015, Marcus Biel, http://www.marcus-biel.com/

Besides the different data structures of ArrayList and LinkedList, LinkedList also implements the Queue and the Deque interfaces which gives it some additional functionality over ArrayList.

ArrayList vs. LinkedList

ImplementsExtends

Collection

List

QueueLinkedList

Deque

ArrayList

In conclusion, there is no overall winner between ArrayList and LinkedList. Your specific requirements will determine which class to use.

2015, Marcus Biel, http://www.marcus-biel.com/

In conclusion, there is no overall winner between ArrayList and LinkedList. Your specific requirements will determine which class to use.

LinkedList

ImplementsExtends

Collection

List

QueueLinkedList

Deque

Lets put ArrayList aside for now and have an in-depth look at the LinkedList implementation.

2015, Marcus Biel, http://www.marcus-biel.com/

Lets put ArrayList aside for now and have an in-depth look at the LinkedList implementation.

LinkedListHere is a simplified code excerpt from the java.util.LinkedList class.package java.util;

public class LinkedList implements List,Deque{

private Node first; private Node last;

public E get(int index) {} public boolean add(E e) {} public E remove(int index) {}

[]}

2015, Marcus Biel, http://www.marcus-biel.com/

Here is a simplified code excerpt from the java.util.LinkedList class.

package java.util;

public class LinkedList implements List,Deque{

private Node first; private Node last;

public E get(int index) {} public boolean add(E e) {} public E remove(int index) {}

[]}LinkedListI dont expect you to fully grasp every detail of the code, I just want to show you that LinkedList is a normal Java class which anyone could have written, given enough time and knowledge.

2015, Marcus Biel, http://www.marcus-biel.com/

I dont expect you to fully grasp every detail of the code, I just want to show you that LinkedList is a normal Java class which anyone could have written, given enough time and knowledge.

package java.util;

public class LinkedList implements List,Deque{

private Node first; private Node last;

public E get(int index) {} public boolean add(E e) {} public E remove(int index) {}

[]}LinkedListThe real source code is available online. After finishing this presentation, I recommend that you take a look at it for yourself.

2015, Marcus Biel, http://www.marcus-biel.com/

The real source code is available online. After watching this episode, I recommend that you take a look at it for yourself.

package java.util;

public class LinkedList implements List,Deque{

private Node first; private Node last;

public E get(int index) {} public boolean add(E e) {} public E remove(int index) {}

[]}LinkedListSo, as you can see, LinkedList implements the List, Queue and Deque interfaces, as Deque extends the Queue interface.

2015, Marcus Biel, http://www.marcus-biel.com/

Okay. So, as you can see, LinkedList implements the List, Queue and Deque interfaces, as Deque extends the Queue interface.

package java.util;

public class LinkedList implements List,Deque{

private Node first; private Node last;

public E get(int index) {} public boolean add(E e) {} public E remove(int index) {}

[]}LinkedListNext you can see that the LinkedList class has a reference to the first and the last elements of the list.

2015, Marcus Biel, http://www.marcus-biel.com/

Next you can see that the LinkedList class has a reference to the first and the last elements of the list.

package java.util;

public class LinkedList implements List,Deque{

private Node first; private Node last;

public E get(int index) {} public boolean add(E e) {} public E remove(int index) {}

[]}LinkedListFinally, you can see that the class has functions like- get, add or remove to access, insert or delete elements from the list.

2015, Marcus Biel, http://www.marcus-biel.com/

Finally, you can see that the class has functions like get, add or remove - to access, insert or delete elements from the list.

Doubly Linked List233

17

9

42

As we just saw in the code, the LinkedList class has a reference to the first and last elements of the list, shown as red arrows in this slide.

2015, Marcus Biel, http://www.marcus-biel.com/

As we just saw in the code, the LinkedList class has a reference to the first and last elements of the list, shown as red arrows in this slide.

Doubly Linked List233

17

9

42

Every single element in a Doubly Linked List has a reference to its previous and next elements as well as a reference to an item, simplified as a number within a yellow box on this slide.

2015, Marcus Biel, http://www.marcus-biel.com/

Every single element in a Doubly Linked List has a reference to its previous and next elements as well as a reference to an item, simplified as a number within a yellow box on this slide.

public class Node { private E item; private Node previous; private Node next; public Node(E element, Node previous, Node next) { this.item = element; this.next = next; this.previous = previous; }}

NodeHere you see a code excerpt of a Node. It has private members for the item it holds, and for the previous and next Node in the list.

2015, Marcus Biel, http://www.marcus-biel.com/

Here you see a code excerpt of a Node. It has private members for the item it holds, and for the previous and next Node in the list.

package java.util;

public class LinkedList implements List,Deque{

private Node first; private Node last;

public E get(int index) {} public boolean add(E e) {} public E remove(int index) {}

[]}LinkedListAs a user of the Collections class LinkedList, you never directly access the Nodes.

2015, Marcus Biel, http://www.marcus-biel.com/

As a user of the Collections class LinkedList, you never directly access the Nodes.

package java.util;

public class LinkedList implements List,Deque{

private Node first; private Node last;

public E get(int index) {} public boolean add(E e) {} public E remove(int index) {}

[]}LinkedListInstead you use the public methods of the LinkedList class that internally operate on the private Node members.

2015, Marcus Biel, http://www.marcus-biel.com/

Instead you use the public methods of the LinkedList class that internally operate on the private Node members.

java.util.List

ListLinkedList

In my tutorial about ArrayList , I introduced you to the methods of the List interface, so I wont mention about those methods again.

2015, Marcus Biel, http://www.marcus-biel.com/

In the tutorial about ArrayList(http://www.marcus-biel.com/arraylist/). I introduced you to the methods of the List interface, so I wont mention about those methods again.

java.util.Queue

QueueLinkedList

Instead, lets go on and look at the methods of the Queue interface implemented by LinkedList.

2015, Marcus Biel, http://www.marcus-biel.com/

Instead, lets go on and look at the methods of the Queue interface implemented by LinkedList.

Operations on a Queueend (tail)front (head)23317942From a high level perspective, the Queue interface consists of three simple operations:

2015, Marcus Biel, http://www.marcus-biel.com/

From a high level perspective, the Queue interface consists of three simple operations:

add elementretrieve elementretrieve and remove elementOperations on a Queueadd an element to the end of the Queue

2015, Marcus Biel, http://www.marcus-biel.com/

add an element to the end of the Queue

add elementretrieve elementretrieve and remove elementOperations on a Queueretrieve an element from the front of the Queue, without removing it.

2015, Marcus Biel, http://www.marcus-biel.com/

retrieve an element from the front of the Queue, without removing it.

add elementretrieve elementretrieve and remove elementOperations on a Queuebut of course the operation returns a reference to the object and does not copy it.

2015, Marcus Biel, http://www.marcus-biel.com/

In the illustration the blue guy was copied, but of course the operation returns a reference to the object and does not copy it.

add elementretrieve elementretrieve and remove elementOperations on a QueueOkay. Finally you can retrieve and remove an element from the front of the Queue.

2015, Marcus Biel, http://www.marcus-biel.com/

Okay. Finally you can retrieve and remove an element from the front of the Queue.

Specific Events on a QueueIn the lifetime of a Queue, there are special situations,

2015, Marcus Biel, http://www.marcus-biel.com/

In the lifetime of a Queue, there are special situations,

Specific Events on a Queue?

like trying to remove an elementfrom an empty Queue

2015, Marcus Biel, http://www.marcus-biel.com/

from an empty Queue

Specific Events on a Queueor trying to add an element to a Queue that has a limited capacity and is currently full.23317942392511162034

2015, Marcus Biel, http://www.marcus-biel.com/

or trying to add an element to a Queue that has a limited capacity and is currently full.

return special valuethrow ExceptionSpecific Events on a QueueDepending on your specific implementation, this might be an expected situation and you need a method that returns null or false in this case.

2015, Marcus Biel, http://www.marcus-biel.com/

Depending on your specific implementation, this might be an expected situation and you need a method that returns null or false in this case.

return special valuethrow ExceptionSpecific Events on a QueueAlternatively this might be an unexpected situation and you need a method that throws an Exception in this case.

2015, Marcus Biel, http://www.marcus-biel.com/

Alternatively this might be an unexpected situation and you need a method that throws an Exception in this case.

java.util.QueueThrows ExceptionReturns Special ValueAddaddOfferRetrieveelementPeekRetrieve & RemoveRemovePoll

The Queue interface offers each of its operations in two flavours one method that will throw an Exception, and one that will return a special value in certain cases. lets look at this in more detail.

2015, Marcus Biel, http://www.marcus-biel.com/

Therefore, the Queue interface offers each of its operations in two flavours - one method that will throw an Exception, and one that will return a special value in certain cases. Okay, lets look at this in more detail.

Add elementsboolean add(Ee)boolean offer(Ee)A Queue allows to add elements to the end of the Queue.

2015, Marcus Biel, http://www.marcus-biel.com/

A Queue allows to add elements to the end of the Queue.

Add elementsboolean add(Ee)boolean offer(Ee)add will throw an Exception when the Queue is full, while offer will return false in this case.

2015, Marcus Biel, http://www.marcus-biel.com/

add will throw an Exception when the Queue is full, while offer will return false in this case.

Add elementsboolean add(Ee)boolean offer(Ee)LinkedList, like most Queue implementations, has an unlimited capacity, so it will never be full.

2015, Marcus Biel, http://www.marcus-biel.com/

LinkedList, like most Queue implementations, has an unlimited capacity, so it will never be full.

Add elementsboolean add(Ee)boolean offer(Ee)ArrayBlockingQueue on the other hand is a Queue implementation that has a limited capacity.

2015, Marcus Biel, http://www.marcus-biel.com/

ArrayBlockingQueue on the other hand is a Queue implementation that has a limited capacity.

Retrieve elementsE element()E peek()Next, element and peek allow you to retrieve an element from the front of the Queue, without removing it.

2015, Marcus Biel, http://www.marcus-biel.com/

Next, element and peek allow you to retrieve an element from the front of the Queue, without removing it.

Retrieve elementsE element()E peek()If the Queue is empty, the element function will throw an Exception, while peek() will return false.

2015, Marcus Biel, http://www.marcus-biel.com/

If the Queue is empty, the element function will throw an Exception, while peek() will return false.

Retrieve & remove elementsE remove()E poll()Finally you can retrieve and remove an element from the front of the Queue. If the Queue is empty, remove will throw an Exception, while poll will return false.

2015, Marcus Biel, http://www.marcus-biel.com/

Finally you can retrieve and remove an element from the front of the Queue. If the Queue is empty, remove will throw an Exception, while poll will return false.

java.util.Deque

DequeLinkedList

Okay, now we will look at some methods of the Deque interface, as implemented by LinkedList.

2015, Marcus Biel, http://www.marcus-biel.com/

Okay, now we will look at some methods of the Deque interface, as implemented by LinkedList.

java.util.Deque

DequeLinkedList

Deque is the short form of Double Ended Queue

2015, Marcus Biel, http://www.marcus-biel.com/

Deque is the short form of Double Ended Queue

java.util.Deque

DequeLinkedList

so it is a Queue that can be accessed from either end.

2015, Marcus Biel, http://www.marcus-biel.com/

so it is a Queue that can be accessed from either end.

java.util.Dequethrows Exceptionreturns special valueAddaddFirstaddLastofferFirstofferLastRetrievegetFirstgetLastpeekFirstpeekFirstRetrieve & RemoveremoveFirstremoveLastpollFirstpollLast

Just like a Queue, a Deque allows adding, retrieving and - retrieving and removing - an element.

2015, Marcus Biel, http://www.marcus-biel.com/

Just like a Queue, a Deque allows adding, retrieving and - retrieving and removing - an element.

java.util.Dequethrows Exceptionreturns special valueAddaddFirstaddLastofferFirstofferLastRetrievegetFirstgetLastpeekFirstpeekFirstRetrieve & RemoveremoveFirstremoveLastpollFirstpollLast

But as it can be accessed from either end, the Queue methods we saw before now exist in two variations one for the first and one for the last element in the Deque.

2015, Marcus Biel, http://www.marcus-biel.com/

But as it can be accessed from either end, the Queue methods we saw before now exist in two variations - one for the first and one for the last element in the Deque.

java.util.Dequethrows Exceptionreturns special valueAddaddFirstaddLastofferFirstofferLastRetrievegetFirstgetLastpeekFirstpeekFirstRetrieve & RemoveremoveFirstremoveLastpollFirstpollLast

Again, lets look at this in more detail.

2015, Marcus Biel, http://www.marcus-biel.com/

Again, lets look at this in more detail.

Add elementsYou can add elements to both ends of the Deque.

2015, Marcus Biel, http://www.marcus-biel.com/

You can add elements to both ends of the Deque.

Add elementsvoid addFirst(Ee)Just like the add method of the Queue interface, addFirst

2015, Marcus Biel, http://www.marcus-biel.com/

Just like the add method of the Queue interface, addFirst

Add elementsvoid addFirst(Ee)void addLast(Ee)and addLast will throw an Exception when the Deque is full.

2015, Marcus Biel, http://www.marcus-biel.com/

and addLast will throw an Exception when the Deque is full.

Add elements317942

boolean offerFirst(Ee)offerFirst

2015, Marcus Biel, http://www.marcus-biel.com/

offerFirst

Add elements317922boolean offerFirst(Ee)boolean offerLast(Ee)and offerLast will return false instead of throwing an Exception.

2015, Marcus Biel, http://www.marcus-biel.com/

and offerLast will return false instead of throwing an Exception.

Add elementsboolean offerFirst(Ee)boolean offerLast(Ee)Please keep in mind that LinkedList has an unlimited capacity, so it will never be full.

2015, Marcus Biel, http://www.marcus-biel.com/

Please keep in mind that LinkedList has an unlimited capacity, so it will never be full.

Add elementsboolean offerFirst(Ee)boolean offerLast(Ee)LinkedBlockingDeque on the other hand is a Deque implementation-that may have a limited capacity. Okay, lets go on.

2015, Marcus Biel, http://www.marcus-biel.com/

LinkedBlockingDeque on the other hand is a Deque implementation that may have a limited capacity. Okay, lets go on.

Retrieve elementsYou can retrieve elements from both ends of the Deque, without removing them.

2015, Marcus Biel, http://www.marcus-biel.com/

You can retrieve elements from both ends of the Deque, without removing them.

Retrieve elementsE getFirst()getFirst

2015, Marcus Biel, http://www.marcus-biel.com/

getFirst

Retrieve elementsE getFirst()E getLast()and getLast will throw an Exception when the Queue is empty,

2015, Marcus Biel, http://www.marcus-biel.com/

and getLast will throw an Exception when the Queue is empty,

Retrieve elementsE peekFirst()while peekFirst

2015, Marcus Biel, http://www.marcus-biel.com/

while peekFirst

Retrieve elementsE peekFirst()E peekLast()and peekLast will return false in this case.

2015, Marcus Biel, http://www.marcus-biel.com/

and peekLast will return false in this case.

Retrieve elementsFinally, you can retrieve and remove elements from both ends of the Deque.

2015, Marcus Biel, http://www.marcus-biel.com/

Finally, you can retrieve and remove elements from both ends of the Deque.

Retrieve elementsE removeFirst()removeFirst

2015, Marcus Biel, http://www.marcus-biel.com/

removeFirst

Retrieve & remove elementsE removeFirst()E removeLast()and removeLast will throw an Exception when the Queue is empty,

2015, Marcus Biel, http://www.marcus-biel.com/

and removeLast will throw an Exception when the Queue is empty,

Retrieve & remove elementsE pollFirst()while pollFirst

2015, Marcus Biel, http://www.marcus-biel.com/

while pollFirst

Retrieve & remove elementsE pollFirst()E pollLast()and pollLast will return false in this case.

2015, Marcus Biel, http://www.marcus-biel.com/

and pollLast will return false in this case.

StackOkay. Now on to a completely different topic.

The Deque interface also supports the methods of the Stack data structure, push peek and pop.

2015, Marcus Biel, http://www.marcus-biel.com/

Okay. Now on to a completely different topic. The Deque interface also supports the methods of the Stack data structure, push peek and pop.

StackTherefore java.util.LinkedList can also be used as Stack.

2015, Marcus Biel, http://www.marcus-biel.com/

Therefore java.util.LinkedList can also be used as Stack.

StackA Stack is a very simple data structure,that can only be accessed from the top. As an analogy, think of a stack of books.

2015, Marcus Biel, http://www.marcus-biel.com/

A Stack is a very simple data structure that can only be accessed from the top. As an analogy, think of a stack of books.

Stackboolean push (Ee)push adds an element to the top of the Stack.

2015, Marcus Biel, http://www.marcus-biel.com/

push adds an element to the top of the Stack.

Stackboolean push (Ee)It is equivalent to the addFirst method.

2015, Marcus Biel, http://www.marcus-biel.com/

It is equivalent to the addFirst method.

StackE peek()peek retrieves but does not remove an element from the top of the Stack.

2015, Marcus Biel, http://www.marcus-biel.com/

peek retrieves but does not remove an element from the top of the Stack.

StackE peek()It is equivalent to the peekFirst method.

2015, Marcus Biel, http://www.marcus-biel.com/

It is equivalent to the peekFirst method.

StackE pop()pop retrieves and removes an element from the top of the Stack.

2015, Marcus Biel, http://www.marcus-biel.com/

pop retrieves and removes an element from the top of the Stack.

StackE pop()It is equivalent to the removeFirst method.

2015, Marcus Biel, http://www.marcus-biel.com/

It is equivalent to the removeFirst method.

Copyright 2016 Marcus BielAll rights reserved

2015, Marcus Biel, http://www.marcus-biel.com/