Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.

Similar presentations


Presentation on theme: "CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost."— Presentation transcript:

1 CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost

2 2 Lecture Outline Data Structures Linked List Iterators

3 3 Arrays The shortcomings Fixed size Insertion into the middle of a contiguous array Removal from the middle of a contiguous array

4 4 Data Structures Objects whose purpose is to organize data (primitives or other objects) Allow us to store large amounts of information when it is not desirable to do so with an array Can grow and shrink as needed Can be more efficient to search than arrays in certain cases

5 5 Data Structures Java Libraries Java provides several data structures in its libraries  Contained in the java.util package [ To the JavaDoc, Batman! ] In the next few weeks we will be exploring some of these Data Structures and learning their strengths and weaknesses  When it is appropriate to use a particular structure

6 6 Linked Lists One of the most basic data structures is the linked list A linked list is a data structure which consists of a number of nodes, each of which has some contents and a reference to the next node (storage) List Node

7 7 Linked Lists Code View A linked list is a data structure which consists of a number of nodes (instances of a Node class), each of which has some contents (instance variable) a reference to the next node (instance variable) Object storage; Node next; class Node Object storage; Node next; Object storage; Node next; class SinglyLinkedList Node head;

8 8 Linked Lists vs. Arrays Adding and removing elements in the middle of a linked list is efficient Visiting the elements of a linked list in sequential order is efficient Random access is not efficient Lists can grow arbitrarily large  (Resizing is efficient)

9 9 Linked Lists Implementation To keep it simple, we will look at implementing a singly-linked list  Called “Singly Linked” because Node s only know about the Node after them (References, or links only go in one direction)  You will be asked to implement a Doubly Linked List in Lab 4

10 10 Linked Lists Implementation Node class  Holds a reference to the next Node  Holds a reference to the Object it is storing SinglyLinkedList class  Holds a reference head to the first node (storage) List Node

11 11 Lists In Code public class Node { Object contents; Node nextNode; public Node (Object contents) { this.contents = contents; } public class SinglyLinkedList { Node head; public SinglyLinkedList () { this.head = null; }

12 12 Adding a New First Element When a new Node is added to the list  It becomes the head of the list  The old list head becomes its next Node public class SinglyLinkedList { //... public void addFirst (Object add) { Node newNode = new Node(add); newNode.next = this.head; this.head = newNode; } }

13 13 Removing the First Element When the first element is removed  The data of the first node are saved and later returned as the method result  The successor of the list head becomes the list head  The old node will be garbage collected when there are no further references to it

14 14 Removing the First Element The removeFirst method public class SinglyLinkedList { //... public Object removeFirst() { if (head == null) return null; Object obj = this.head.contents; this.head = this.head.next; return obj; } }

15 15 Getting an Element by Index The getNth method public Object getNth (int index) { Node search = this.head; for (int i=0; i<index; i++) { if (search == null) return null; search = search.next; } return search.contents; }

16 16 Iterating Over Data Structures Iterating over a Linked List  We could just use a regular for loop: But what is this doing internally? [ Example on Board ]  Very inefficient for (int i=0; i<list.getSize(); i++) { Object nth = list.getNth(i);... // Do something with ‘nth’ }

17 17 Iterators Helpers for Stepping through Data Structures Let’s define a way for users to iterate through our data structure (SinglyLinkedList), one element at a time  Internal Iterator [ Example on Board ] But what if multiple different entities want to iterate over the Data Structure?  Position is invalidated for other users

18 18 Iterators Safely Exporting State What we need is a way to encapsulate (package up) and export a position in the Data Structure…  Allow multiple different simultaneous iterators over the Data Structure  We need to have a trusted way of providing a reference to our internal representation Exporting our internal representation How is this done?

19 19 Levels of Encapsulation Exporting State Safely We want the internal structure ( Node s) of the linked list to be as protected as possible We want to be able to export some notion of a position within the list  The easiest way to do this would be a reference to a Node But we don’t want to expose the Node object itself  Write an encapsulation for the behavior we want to export

20 20 Packages and Access Modifiers Classes that Work Together Closely Put our SinglyLinkedList, our Node, and our ListIterator classes inside of package Declare Node head in SinglyLinkedList with the protected access modifier ListIterator can access protected fields of the List, because List and ListIterator are in the same package Make the constructor of ListIterator protected so that it must be created via the SinglyLinkedList

21 21 Inner Classes In Java, we can define inner classes to encapsulate a subset of behavior  Helper objects Instances of inner classes can access all members of the class inside which they are defined (even private ones!) Preserves a clear division of functionality  Purpose of outer object does not become cluttered Allows us to define “trusted” ways to export an object’s state Enables programmers to use multiple instances of helper objects

22 22 Iterators ListIterator type  Gives access to elements inside a linked list  Encapsulates the concept of a ‘position’ anywhere inside the linked list  Protects the internal structure of the linked list while giving access

23 23 A List Iterator

24 24 List Iterator Think of an iterator as pointing between two elements in a data structure  Analogy: like the cursor in a word processor points between two characters The iterator method of the SinglyLinkedList class gets a new ListIterator  Points to the beginning of the list SinglyLinkedList employeeNames = new SinglyLinkedList(); ListIterator iterator = employeeNames.iterator();

25 25 A Conceptual View of a List Iterator

26 26 List Iterator Initially, the iterator points before the first element hasNext returns true if there is a next element The next method moves the iterator and returns the current item Object next = iterator.next(); if (iterator.hasNext()) iterator.next();

27 27 List Iterator The next method returns the element that the iterator is passing while (iterator.hasNext()) { Object obj = iterator.next(); // Do something with obj }

28 28 LinkedListIterator The LinkListIterator class package listutil; public class LinkedListIterator { Node previous, position; List list; public LinkedListIterator(List list) { this.list = list; this.position = null; this.previous = null; } }

29 29 Linked List Iterator hasNext Method The next method should only be called when the iterator is not at the end of the list  If hasNext returns true The iterator is at the end if…  the list is empty ( list.head == null )  there is no element after the current position ( position.next == null )

30 30 The Linked List Iterator hasNext Method private class LinkedListIterator { //... public boolean hasNext() { if (position == null) return (list.head != null); else return (position.next != null); } //... }

31 31 The Linked List Iterator next Method position: reference to the last visited Node previous: reference to the Node before position next method: position reference is advanced to position.next Last position is remembered in previous If the iterator points before the first element of the list, then the previous is null and position must be set to list.head

32 32 The Linked List Iterator next Method public Object next() { if (!hasNext()) return null; previous = position; // Remember for remove if (position == null) position = list.head; else position = position.next; return position.contents; }

33 33 The Linked List Iterator remove Method If the element to be removed is the first element, call list.removeFirst Otherwise, the node preceding the element to be removed needs to have its next reference updated to skip the removed element

34 34 The Linked List Iterator remove Method public void remove() { if (previous == position) return; // Invalid state! if (position == list.head) { list.removeFirst(); } else { previous.next = position.next; } position = previous; }

35 35 Removing a Node From the Middle of a Linked List

36 36 The Linked List Iterator remove Method: Caveats If the previous equals position :  Then the call to remove does not immediately follow a call to next  Method cannot execute properly (throw an IllegalArgumentException)  It is illegal to call remove twice in a row  remove sets the previous reference to position

37 37 The Linked List Iterator set Method Changes the data stored in the previously visited element The set method public Object set (Object obj) { Object contents = null; if (position != null) { contents = position.contents; position.contents = obj; } return contents; }

38 38 The Linked List Iterator add Method add inserts the new node after the current position The most complex operation is the addition of a node Sets the successor of the new node to the successor of the current position

39 39 The Linked List Iterator's add Method public void add(Object obj) { if (position == null) { list.addFirst(obj); position = list.head; previous = null; } else { Node newNode = new Node(obj); newNode.next = position.next; position.next = newNode; previous = position; position = newNode; } }

40 40 Adding a Node to the Middle of a Linked List

41 41 Conclusion Lab 3 assigned today  Arrays & Iteration  Lab 2 due by midnight  I will be in lab now


Download ppt "CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost."

Similar presentations


Ads by Google