summer 2007cisc121 - prof. mcleod1 cisc121 – lecture 6 last time: –encapsulation –javadoc...

81
Summer 2007 CISC121 - Prof. McLeod 1 CISC121 – Lecture 6 Last time: – Encapsulation Javadoc documentation Testing and Debugging

Upload: emmeline-murphy

Post on 18-Jan-2018

218 views

Category:

Documents


0 download

DESCRIPTION

Summer 2007CISC121 - Prof. McLeod3 You Will Need To: Look at Exercise 3 and start work on Assn 3 – both on Encapsulation. Prepare for midterm: –Krista will hold midterm prep tutorial at 4:30pm in GOO456 (the lab) on Monday. her if you intend to go! –Next Tuesday, the 24 th, at 10am – Note late start! –In BIO1120 (same room as lecture). –Look over and print out a copy of the aid sheet (now posted), if you want to use it.

TRANSCRIPT

Page 1: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 1

CISC121 – Lecture 6• Last time:

– Encapsulation– Javadoc documentation– Testing and Debugging

Page 2: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 2

You Should Be:• Able to apply feedback from Assn 1 to Assn 2.• Just about finished Assn 2.• Finished reading over testing and debugging

notes from last lecture.

Page 3: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 3

You Will Need To:• Look at Exercise 3 and start work on Assn 3 –

both on Encapsulation.

• Prepare for midterm:– Krista will hold midterm prep tutorial at 4:30pm in

GOO456 (the lab) on Monday. E-mail her if you intend to go!

– Next Tuesday, the 24th, at 10am – Note late start!– In BIO1120 (same room as lecture).– Look over and print out a copy of the aid sheet (now

posted), if you want to use it.

Page 4: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 4

Midterm Topics• Fundamental Java, Including:

– Expressions, Loops and Conditionals– Methods– File and Console I/O– Catching Exceptions

• Encapsulation• Testing and Debugging (comprehension only)• Linked Lists

– (Staring, but not finishing, this topic today. I will not ask you anything hard on linked lists on the midterm.)

Page 5: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 5

Midterm Format• All hand-written on paper:

• Short answer comprehension questions.• “What is the Output” questions.• Write or complete or correct a method or program.

Page 6: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 6

Today• Finish up Testing and Debugging by looking at

invariants.• Start Linked Lists

• But first, let’s go over how the debugger works in Eclipse.

Page 7: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 7

Debugging in Eclipse• If you have not used Debug before – the “Debug

Perspective” button will not show up at the top right.

• To use debug mode, you must put a breakpoint into your program, by right-clicking on the bar at the left of your program, and choosing “Toggle Breakpoint”.

• Then choose “Debug As” followed by “Java Application”.

Page 8: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 8

Debugging in Eclipse, Cont.• Now you are in the “Debug Perspective”!

• Lots of fun things to do here!– You can examine the current contents of

variables and objects.– You can continue your program one line of

code at a time.– etc.!

• (Also look at version history in Eclipse…)

Page 9: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 9

• Another logic tool that you can use to prove that your program is “correct” is the use of assertions.

• Special assertions are called:– Preconditions,– Postconditions & – Invariants.

• Essentially, an assertion is just a statement that describes a condition that should be true at a given point in your program.– An assertion could just be a comment.– Java provides the use of the “assert” command, that can do

something useful in the event that the condition turns out to be false.

Program Correctness

Page 10: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 10

Pre- & Post- Conditions• These assertions are made at the beginning of a method

(pre-condition) and at the end of the method (post-condition).

• A precondition:– Specifies what is true before the method executes.– Describes the assumptions under which the method runs.– Satisfying the preconditions is the responsibility of the calling

method (or “user”).

• A postcondition:– Specifies what is true after the method executes.– Describes the effects of the code.– Satisfying the postconditions is the responsibility of the person

coding the method.

Page 11: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 11

Pre- & Post- Conditions - Cont.• These conditions form part of the specifications

of the method.

• A piece of code is said to be correct if the postconditions will be satisfied for all possible states of the preconditions.

• It is not always possible to completely prove correctness by this definition. – Sometimes all you can say is that the postconditions

will be satisfied whenever the method terminates normally.

– This is called partial correctness.

Page 12: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 12

Pre- & Post- Conditions - Cont.• For example, a little method to see if a number is

prime:

public static boolean isPrime (int n) {

for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;

} // end is Prime method

Page 13: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 13

Pre- & Post- Conditions - Cont.• Add pre- and post- conditions:

// pre: n is >= 2public static boolean isPrime (int n) {

for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;

} // end is Prime method// post: true if n is prime, false // otherwise

Page 14: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 14

Invariants• Invariants are assertions that are placed at

strategic positions within the code.• Invariants state what is true at this position.• If the program logic is correct, then one insertion

should lead from the one before and the last insertion should prove the post-condition to be true.

• Next slide has our little method with invariants put in as comments:

Page 15: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 15

// pre: n is >= 2public static boolean isPrime (int n) {

for (int i = 2; i * i <= n; i++) {// inv1: n has no factors between 2 and i-1

if (n % i == 0) {// inv2: i divides n evenly, therefore // n is not primereturn false; }// inv3: n has no factors between 2 and i} // end for loop

// inv4: n has no factors between 2 and// n, therefore n is prime

return true;} // end is Prime method// post: true if n is prime, false otherwise

Page 16: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 16

Invariants - Cont.• Note how the invariants below depend on the

invariants above. The invariant above must be true in order to allow the invariant below to be true.

• Also, the invariants above the return statements, inv3 & inv4, when combined, prove the post-condition to be true.

• So, if you can chain together the invariants between the pre- and post- conditions, and thus prove that the post condition is true, then you have proved the “correctness” of your program.

Page 17: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 17

Invariants - Cont.• In essence, the process is all about forming a

contract between the pre- and post- conditions.

• Having proved the “correctness” of your program, you are now ready to subject your program to a thorough testing with real values.

• Since you can not test every possible input value, your proof of correctness along with some testing must be sufficient to give you confidence that your method works.

Page 18: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 18

Aside – Loop Invariants• “inv1” is called a “loop invariant”, because it is

inside the loop.• For this kind of invariant:

– Make sure it is true when the loop starts.– Make sure it stays true each time through the loop.– Does the invariant lead to the desired condition when

the loop terminates?– Make sure the loop will terminate!

Page 19: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 19

Program Correctness - Cont.• For the example above, you could have walked

through the logic in your head to prove that it works. Was all this fancy stuff necessary?

• The use of assertions has two purposes:– It can help to provide documentation of your code:

• Pre- and Post- conditions are an important part of the documented specifications of your code.

– More complex methods would be difficult to “walk through” without some kind of commenting to indicate the progression of the logic.

Page 20: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 20

Invariants – Triangle Example• Remember the example of the triangles?• It contains a logic error, but no syntax errors – it

compiles and runs fine.• It took many random test cases to determine that

there was a logic error.• Here is the code with assertions (squished…):

Page 21: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 21

// pre: a,b,c > 0 and form a trianglepublic static String testTriangle (int a, int b, int c){ if (a == b) { if (b == c) { return "equilateral";} //inv1: a=b, b=c, a=c else { return "isosceles";} //inv2: a=b, bc, ac } else { if (b == c) { return "isoscles";} //inv3: ab, b=c, ac else { return "scalene";} //inv4: ab, bc, ac or a=c }} //end testTriangle// post: all possibilities have been tested Not so!

Page 22: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 22

Invariants – Triangle Example – Cont.• Now it is easier to see that not all possibilities

have been tested. A situation can be reached where: ab, bc, but a=c is unknown.

• So there is a break in the logic between inv4 and the post condition.

Page 23: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 23

Program Correctness - Cont.• In Java versions > 1.4, assertions can be put in

the code using the “assert” command, where they can actually do something useful.– Use “assert” when you are having problems

debugging a particular piece of code.– You can use a compilation switch to tell the compiler to

ignore all assertions when it does the final compile on your code – this way you don’t have to take them out of the source code!

Page 24: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 24

The Java assert Keyword• Syntax:

assert expression1;assert expression1: expression2;

expression1 must evaluate to a boolean result. For the second syntax, expression2 provides a String for the AssertionError that will be thrown when expression1 evaluates to false.

Page 25: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 25

Using Assertions in Code - Cont.• By default, code is compiled with the assert

command being treated as a comment - so they do not have to be removed when not needed.

• You have to tell the compiler to “enable assertions” for them to work.

• Make sure that your assert statement is passive. It should not “do anything” with variable contents or change how the program runs.– In this way, ignoring the assertions should not affect the

program.

Page 26: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 26

Using assert, Cont.• How is using assert different from just throwing

an exception directly?– It is easier to do, and the invoking method does not

have to worry about catching an exception.– You have the option of compiling and running your

program in such a way that assertions can be ignored, speeding up the execution of your code.

• During program development, enable assertions. Once done, disable them.

• You can leave all your assert statements in your source code!

Page 27: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 27

Aside – Using Assertions in Eclipse• To add the command line parameter: “-ea” for “enable assertions”

– Go to “Run” on the menu bar, then choose “Run…”.– In the window that opens, choose the “Arguments” tab

and enter “-ea” (without the quotes) in the “VM arguments” box.

• This parameter gets reset when you exit Eclipse.• To set permanently:

– Go to “Window”, “Preferences…”, “Java”, “Installed JREs” and choose “jre1.6.0” and then click on the “Edit” button. Add “-ea” to “Default VM Arguments”.

Page 28: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 28

Best Reference on Assertions• http://java.sun.com/j2se/1.5.0/docs/guide/

language/assert.html

Page 29: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 29

Creating a Data Structure• Why create our own data structures when there

are so many pre-defined in the Java API already? (Lets have a look in java.util in the API docs…)

• To learn how they are put together.• Avoid including extra methods that are not

needed. (Tighter, more efficient code.)• Specific structure for our requirements, not using

a generic structure.• Avoid privacy leaks.

Page 30: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 30

Comparison of Arrays, ArrayLists and Linked Lists

• Arrays can be useful because:– The convenient “[]” notation allows immediate access

to any element in the array.– Arrays can directly hold primitive types, as well as

objects.– Primitive type storage is memory efficient, since the

use of a Wrapper class is not necessary.

Page 31: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 31

Comparison of Arrays, ArrayLists and Linked Lists - Cont.

• Arrays can be a problem because:– The size of the array must be known or at least

estimated before the array can be used.– Increasing the size of an array can be very time

intensive. How would you do this?– Arrays can only use a contiguous block of memory.

When a new element is inserted into an array, all elements above the new one must be shifted up.

Page 32: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 32

Comparison of Arrays, ArrayLists and Linked Lists – Cont.

• ArrayLists are useful because:– Sizing is no longer a problem.– They are built-in to the java.util class.– They inherit many useful methods.– ArrayList<T> (The generic ArrayList class.) elements

do not need to be cast back to the original element type.

– Automatic boxing and un-boxing in Java >= 5.0

Page 33: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 33

Comparison of Arrays, ArrayLists and Linked Lists – Cont.

• An ArrayList can be a problem because:– Arrays are still used (in the background).– Every re-sizing of the ArrayList causes a time lag, since

a new array must be created in another block of memory and all the elements copied over.

– Element insertion is just as time-consuming as with arrays, and possibly even worse if the ArrayList has to be resized.

– It can only store Objects, not primitive types.– Do not have the handy “[]” notation, only methods.

Page 34: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 34

Linked Lists• A singly linked list consists of Objects called “nodes”

that contain data and a link to the next node in the list:

• A node is defined in one class, and another class, the linked list class, contains the “head” and “tail” pointers.

• More detail shortly!

15

head

10 5null

20

tail

Page 35: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 35

Comparison of Arrays, ArrayLists and Linked Lists – Cont.

• Linked lists are useful because:– Can store primitive types or Objects or any

combination of the above.– A node can be anywhere in memory. The list does not

have to occupy a contiguous memory space.– List size is only limited by available memory, and does

not have to be declared first.– No empty nodes.– The adding, insertion or deletion of list elements or

nodes can be accomplished with the minimal disruption of neighbouring nodes.

Page 36: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 36

Comparison of Arrays, ArrayLists and Linked Lists – Cont.

• Problems with linked lists include:– A node is not necessarily an efficient storage Object (in

terms of memory usage), since it must hold links to other nodes in addition to the data item(s).

– In order to access any one node in a linked list, all links must be followed from the “head” of the list to get to that certain node. Nothing like the “[]” notation of arrays.

Page 37: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 37

Singly Linked List - Node Classpublic class IntNode {

public int info; // a data valuepublic IntNode next; // a link

// constructorspublic IntNode (int i) { this(i, null); }public IntNode (int i, IntNode n) {

info = i;next = n;

}} // end IntNode

Page 38: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 38

Singly Linked List – Cont.• The “data value” could just as easily be an Object

(of any kind):public class GNode {

public Object info; //a data Objectpublic GNode next; // a link

// constructorspublic GNode (Object newInfo) { this(newInfo, null); }public GNode (Object newInfo, GNode n) {

info = newInfo; // should clone newInfo…next = n;

}} // end GNode

Page 39: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 39

• For simplicity, we will continue to consider a link holding an int value, “info”.

• For example, create a linked list of three integers, 10, 8 and 50:

Singly Linked List – Cont.

Page 40: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 40

Singly Linked List – Cont.• First statement:

IntNode p = new IntNode(10);• As usual, this operation takes place in four

stages:

pinfo:next:

p10

p10null

p10null

(i) (ii)

(iii) (iv)

Page 41: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 41

• The above initialization uses the first constructor, which sets the value of info to 10 and sets the value of next to null.

• The next node is created using

p.next = new IntNode(8);

Singly Linked List – Cont.

Page 42: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 42

Singly Linked List – Cont.p.next = new IntNode(8);

p10null

p10null

8

p10null

8null

p10 8

null

Page 43: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 43

• The last node (50) is added using:

p.next.next = new IntNode(50);

Singly Linked List – Cont.

p10 8 50

null

Page 44: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 44

Singly Linked List – Cont.• Note that the last node always contains null.• Right now, the list is only accessible through the

variable “p”, so the cumbersome chain of “next”’s must be used to get at the individual elements.

• (What happens to the list if you coded “p = null;”?)

• Introduce another class that will keep track of the head and tail positions of the list:

Page 45: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 45

public class IntSLList { // A “singly linked// list with a head and tail”private IntNode head;private IntNode tail;

public IntSLList () {head = null;tail = null;}public void addToHead (int aNum) {head = new IntNode(aNum, head);if (tail == null) tail = head;}// more methods to be developed!

} // end IntSLList

Page 46: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 46

Singly Linked List - Node Class (again)public class IntNode {

public int info; // a data valuepublic IntNode next; // a link

// constructorspublic IntNode (int i) { this(i, null); }public IntNode (int i, IntNode n) {

info = i;next = n;

}} // end IntNode

Page 47: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 47

Singly Linked List – Cont.

• Create a list using:

IntSLList list = new IntSLList();

nullnull

headtail

list

Page 48: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 48

Singly Linked List – Cont.list.addToHead(5); // step ilist.addToHead(10); // step iilist.addToHead(15); // step iii

5null

list

head

tail

10head

tail

5null

15head

tail

10 5null

IntNode’s

Page 49: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 49

Singly Linked List – Cont.• Now either end of the linked list can be located

using the head or tail pointers, without using a cumbersome chain of next’s.

Page 50: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 50

Singly Linked List – Cont.• Simplify notation. This:

• Is the same as:

15head

tail

10 5null

15head

tail

10 5null

Page 51: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 51

Singly Linked List – Cont.

• Mechanism of adding another node:

list.addToHead(20);

• addToHead method:

public void addToHead (int aNum) {head = new IntNode(aNum, head);if (tail == null) tail = head;

}

Page 52: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 52

Singly Linked List – Cont.

15head tail

10 5null

15head

10 5null

20

15head

10 5null

20

15head

10 5null

20

tail

tail

tail

Page 53: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 53

Singly Linked List – Cont.• A method to add a new node to the tail of the list:

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

}public void addToTail (int aNum) {if (!isEmpty()) {tail.next = new IntNode(aNum);tail = tail.next;else {head = new IntNode(aNum);tail = head;}

} // end addToTail

Page 54: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 54

Singly Linked List – Cont.list.addToTail(-5);

15head

10 5null

20tail

15head

10 5null

20tail

-5

15head

10 5null

20tail

-5null

15head

10 520tail

-5null

15head

10 520tail

-5null

Page 55: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 55

Singly Linked List – Cont.

• Why not use: tail = new IntNode(aNum); instead of:tail.next = new IntNode(aNum);tail = tail.next;?

• How would you add a node at the end of the linked list without a tail pointer?

• Does it make sense to sort a linked list?

• Can a node be inserted in the middle of the list, as easily as at the head or tail? Why would you want to?

Page 56: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 56

Singly Linked List – Use of Inner Classes• The node object, IntNode, is a public class and

its attributes (info and next) are public.• This is necessary so that the IntSLList class

can use the node class.• This is not good encapsulation practice.• But if the class IntNode and its attributes are

declared private, how can they be used by the linked list class?

Page 57: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 57

Use of Inner Classes - Cont.• Remember how private attributes are available

(their “scope”) anywhere inside a class, but not outside the class?

• In fact, within the class, it does not matter if an attribute is private or public.

• Re-define IntSLList as:

Page 58: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 58

Use of Inner Classes – Cont.public class IntSLList {

private IntNode head;private IntNode tail;

private class IntNode {private int info;private IntNode next;public IntNode (int i) { this(i, null); }public IntNode (int i, IntNode n) {info = i; next = n;}} // end IntNode

// rest of IntSLList methods, constructors} // end IntSLList

Page 59: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 59

Use of Inner Classes – Cont.

• Note that even though the inner class is private it can be used by IntSLList because it has been defined inside of this class.

• Or, the scope of IntNode is anywhere inside the IntSLList class.

• IntNode and its attributes are *not* available outside IntSLList.

Much Better!

Page 60: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 60

Writing Linked List Methods• Note that each method must work for:

– An empty list,– A list with just one node, and– A list with two or more nodes.

• We have methods to:– Create a list (the constructor)– Add to the head of the list– Check for an empty list– Add to the tail of the list

• What other methods would be useful?

Page 61: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 61

Singly Linked List - Other Methods• Deleting a head node.• Deleting all nodes!• Deleting an inner node (not head or tail).• Deleting a tail node.• Others:

– Searching for a certain node.– Counting nodes.– Adding a inner node (“insertion”, but why?)

Page 62: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 62

Singly Linked List - Deleting Nodes• Note that a deleting method may or may not

return the data value or a link to the data Object that it has deleted. We will assume that the deleting method returns the value.

• The calling method can choose not to do anything with this value.

• Note that these deleting methods will return a value of -1 if the list is empty. What else could we do here?

Page 63: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 63

Deleting the Head Node public int removeFromHead () { if (isEmpty()) return -1; int i = head.info; if (head.next == null) { head = null; tail = null; } else head = head.next; return i; } // end removeFromHead

Page 64: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 64

Deleting the Head Node, Cont.

15head

tail

10 5null

15

head tail

10 5null

• After head = head.next;

• What happens to the node with 15?

Page 65: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 65

Deleting All Nodespublic void clearList() {

if (!isEmpty()) {head = null;tail = null;

} // end if} // end clearList

• Nodes that are no longer “pointed to” are garbage collected!

Page 66: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 66

• First, locate the node, then delete it.

• It is way too big a method to show on this slide!!• See the next one:

Deleting the Node that Contains the Value “delNum”

Page 67: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 67

public void delete (int delNum) { // does not return iif (!isEmpty())if (head==tail && delNum==head.info) { head = null; tail = null;} // only 1 nodeelse if (delNum == head.info) // delete first node, more nodes in list head = head.next;else { IntNode pred = head; IntNode temp = head.next; while (temp != null && temp.info != delNum) {pred = pred.next;temp = temp.next; } // end while if (temp != null) {pred.next = temp.next;if (tail == temp) tail = pred; } // end if} // end else

} // end delete method

Page 68: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 68

Deleting an Inner Node - An Examplelist.delete(10);

15

head

10 520tail

-5null

15head

10 520tail

-5null

15head

10 520tail

-5null

pred temp

pred temp

pred temp

pred.next = temp.next;

Page 69: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 69

Deleting an Inner Node – Iterators• Note the use of the pred and temp objects in

the delete method:– (“Java jargon”) These are called “iterators”

because they are used to move through the list.

Page 70: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 70

Deleting a Tail Node• So how is this going to work?

• How can the tail pointer be moved up to the preceding node?

15

head

10 5null

20

tail

Page 71: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 71

Deleting a Tail Node - Cont.• Since there is no link from the tail node to the

previous node, the only way is to iterate through the entire list, starting from the head, until the tail is reached.

• (How can you tell when you have reached the tail?)

• Two iterators must be used (Why?), as in the delete method:

Page 72: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 72

public int removeTail () {int i = -1;if (!isEmpty()) {i = tail.info;if (head == tail) {head = null; tail = null;} else { IntNode pred = head; IntNode temp = head.next; while (temp.next != null) {pred = pred.next;temp = temp.next; } // end while tail = pred; tail.next = null;} // end else} // end ifreturn i;

} // end removeTail method

Page 73: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 73

Deleting a Tail Node - Cont.• That was a lot of work!• Deleting the tail node this way is more time

consuming than deleting an inner node.• Would it not be nice if the tail node already had a

link pointing to the previous node?

• No problem! Create a doubly linked list.

Page 74: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 74

Doubly Linked Listspublic class IntDLList {

private IntDLNode head;private IntDLNode tail;

private class IntDLNode {private int info;private IntDLNode next;private IntDLNode prev; // new link!public IntDLNode (int aNum) {this(aNum, null, null); }public IntDLNode (int aNum, IntDLNode n, IntDLNode p) {info = aNum; next = n; prev = p; }} // end IntDLNode// IntDLList constructors and methods

} // end IntDLList

Page 75: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 75

Doubly Linked List – Cont.• Structure:

head20

tail

null

10 5nullnext

prev

Page 76: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 76

Doubly Linked List – Cont.• To add a node to the tail of the list:

// better add a constructor too!public IntDLList () {

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

return head == null; }public void addToTail (int aNum) {

if (!isEmpty()) {tail = new IntDLNode(aNum, null, tail);tail.prev.next = tail;} else {head = new IntDLNode(aNum);tail = head;}

} // end addToTail

Page 77: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 77

Doubly Linked List – Cont.

dLList.addToTail(-10);head

20tail

null

10 5null

head20

tail

null

10 5null

-10null

head

20

tail

null

10 5 -10null

-10null

After “new…”:

After tail.prev.next = tail;

After tail=…;

Page 78: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 78

Doubly Linked List – Cont.• To remove the tail node:

public int removeFromTail () {int i = -1;if (!isEmpty()) {i = tail.info;if (head == tail) { // one node in listhead = null; tail = null;}else {tail = tail.prev;tail.next = null;}} // end ifreturn i;

} // end removeFromTail

Page 79: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 79

Doubly Linked List – Cont.

int temp = dLList.removeFromTail();head

20

tail

null

10 5 -10null

After tail = tail.prev;

Before

head

20

tail

null

10 5 -10null

After tail.next = null;head

20

tail

null

10 5null

-10null

temp is -10

Page 80: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 80

Doubly Linked List – Cont.• Now the removeFromTail method is much easier.• So, adding or deleting head or tail nodes is “easy”

- which operations will require iteration?

Any operation that involves a node other than the head or tail!

Page 81: Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 6 Last time: –Encapsulation –Javadoc documentation –Testing and Debugging

Summer 2007 CISC121 - Prof. McLeod 81

Sample Code• See IntDLList.java, for example.