
70720fd56cc84457b1e171cad58ed9d1.ppt
- Количество слайдов: 119
Programming and Problem Solving With Java Chapter 12: Lists Writing List. Classes Example: Infinite Precision Arithmetic Example: Sorting a Lsit Example: A Set Type Doubly Linked Lists Computer Security Programming and Problem Solving With Java Copyright 1999, James M. Slack
Introduction ²Dynamic data structure Grows and shrinks as program runs Example: Java’s standard Vector class ²Lists Used often in everyday life (groceries, to-do, …) ²Will also look at sets in this chapter ²Dynamic data structures in later chapters Stacks Queues Trees Programming and Problem Solving With Java 2
Introduction ²Characteristics of lists There’s a first element There’s a last element All others have predecessor and successor ²Operations on lists Add element Delete element Search for element Sort the elements Programming and Problem Solving With Java 3
Writing List Classes: Char. List ²Character list class Allows adding and deleting characters from either end ²Operations to. String insert. First insert. Last empty remove. First remove. Last Programming and Problem Solving With Java Returns contents in a string. Put new character value at beginning Put new character value at end Returns true if empty Remove node at beginning, return value Remove node at end, return value 4
Writing List Classes: Char. List ²Short example // Short demonstration of how to use the Char. List // class import Char. List; public class Demo. Char. List { public static void main(String[] args) { Char. List my. Char. List = new Char. List(); [H i ! ] Removed H [i ! ] // Insert some characters my. Char. List. insert. First('i'); my. Char. List. insert. Last('!'); my. Char. List. insert. First('H'); // Use the to. String() method System. out. println(my. Char. List); // Remove character System. out. println("Removed " + my. Char. List. remove. First()); } } // Use the to. String() method again System. out. println(my. Char. List); Programming and Problem Solving With Java 5
Writing List Classes: Char. List ²Longer example (uses Text. Menu class) // This program lets you add characters onto // // either end of a linked list, and remove them from either end. It makes sure you don't try to remove characters from an empty list. This is a demonstration of how to use the Char. List class. import Keyboard; import Text. Menu; import Char. List; public class Char. List. Test extends Text. Menu { static final int ADD_FIRST_COMMAND = 1; static final int ADD_LAST_COMMAND = 2; static final int REMOVE_FIRST_COMMAND = 3; static final int REMOVE_LAST_COMMAND = 4; // Constructor - set up menu for the editor public Char. List. Test() { super("Character List Menu"); list = new Char. List(); add. Selection("Add first", '1', ADD_FIRST_COMMAND); add. Selection("Add last", '2', ADD_LAST_COMMAND); add. Selection("Remove first", '3', REMOVE_FIRST_COMMAND); add. Selection("Remove last", '4', REMOVE_LAST_COMMAND); add. Selection("Quit", '5', Text. Menu. QUIT); } Programming and Problem Solving With Java 6
Writing List Classes: Char. List // Event dispatcher public int handle. Event(int event) throws java. io. IOException { switch (event) { case ADD_FIRST_COMMAND: list. insert. First(Keyboard. read. Char( "Enter character to add to beginning: ")); break; case ADD_LAST_COMMAND: list. insert. Last(Keyboard. read. Char( "Enter character to add to end: ")); break; case REMOVE_FIRST_COMMAND: if (list. empty()) { System. out. println("List is empty!"); } else { System. out. println("Removed " + list. remove. First() + " from beginning of list"); } break; case REMOVE_LAST_COMMAND: if (list. empty()) { System. out. println("List is empty!"); } else { System. out. println("Removed " + list. remove. Last() + " from end of list"); } break; } System. out. println("List is now: " + list); return event; } Programming and Problem Solving With Java 7
Writing List Classes: Char. List // Instance variables Char. List list; public static void main(String[] args) throws java. io. IOException { Char. List. Test list. Example = new Char. List. Test(); } } list. Example. run(); +--- Character List Menu --| 1) Add first 2) Add last | 4) Remove last 5) Quit | Enter selection: 1 Enter character to add to beginning: b List is now: [b ] +--- Character List Menu --| 1) Add first 2) Add last | 4) Remove last 5) Quit | Enter selection: 1 Enter character to add to beginning: a List is now: [a b ] +--- Character List Menu --| 1) Add first 2) Add last | 4) Remove last 5) Quit | Enter selection: 2 Enter character to add to end: c List is now: [a b c ] Programming and Problem Solving With Java 3) Remove first 8
Writing List Classes: Char. List ²Char. List is linked structure: each character on the list keeps track of its successor ²Char. List. Node is separate class Space for the character Reference to next character in list Last node references null (special value) Programming and Problem Solving With Java 9
Writing List Classes: Char. List ²Char. List. Node class Char. List. Node { // Constructor public Char. List. Node(char item, Char. List. Node next) { set. Item(item); set. Next(next); } // get. Item: Returns the item value public char get. Item() { return item; } // get. Next: Returns the next item public Char. List. Node get. Next() { return next; } // set. Item: Sets the item to the given value public void set. Item(char item) { this. item = item; } // set. Next: Sets the next item to the given object public void set. Next(Char. List. Node next) { this. next = next; } // Instance vaiables private char item; private Char. List. Node next; Programming} Problem Solving With Java and 10
Writing List Classes: Char. List ²Char. List class References first and last nodes of the list Constructor // Default constructor public Char. List() { first = null; last = null; num. Nodes = 0; } Programming and Problem Solving With Java Makes empty Char. List 11
Writing List Classes: Char. List ²Inserting a new node: insert. First() // insert. First: Inserts a new item at the beginning of the list. public void insert. First(char item) { Char. List. Node new. Node = new Char. List. Node(item, first); } num. Nodes++; first = new. Node; if (last == null) { // Special case: An empty list. // This new node is the last node in the list. last = new. Node; } Programming and Problem Solving With Java 12
Writing List Classes: Char. List ²Inserting a new node: insert. Last() of the list // insert. Last: Inserts a new item at the end public void insert. Last(char item) { Char. List. Node new. Node = new Char. List. Node(item, null); } num. Nodes++; if (first == null) { // Special case: this node is the first node in the list. first = new. Node; } else { // General case: this is not the only node in the list. // Make the last node point to this one and make this // the new last node. last. set. Next(new. Node); } last = new. Node; Programming and Problem Solving With Java 13
Writing List Classes: Char. List ²Removing a node: remove. First() Programming and Problem Solving With Java 14
Writing List Classes: Char. List ²Removing a node: remove. First() // remove. First: Remove the first element from the list and // return its value. If item is current. Node, // then sets current. Node to next node, unless // deleting the last node. In that case, sets // current. Node to previous node. // Note: The list cannot be empty public char remove. First() { Debug. assert(!empty(), "Char. List. remove. First(): List is empty"); Char. List. Node node = first; // Remove the first node from the list. first = first. get. Next(); if (empty()) { // Special case: this is the only node in the list. last = null; } num. Nodes--; } // Return the value of the removed node. return node. get. Item(); Programming and Problem Solving With Java 15
Writing List Classes: Char. List ²Removing a node: remove. Last() Programming and Problem Solving With Java 16
Writing List Classes: Char. List ²Removing a node: the last element from the list and remove. Last() // remove. Last: Remove // return its value. If item is current. Node, // then sets current. Node to next node, unless // deleting the last node. In that case, sets // current. Node to previous node. // Note: The list cannot be empty public char remove. Last() { Debug. assert(!empty(), "Char. List. remove. Last(): List is empty"); Char. List. Node node = last, previous. Node; if (last == first) { // Special case: only one node in the list last = first = null; } else { // General case: find second-to-last node previous. Node = first; while (previous. Node. get. Next() != last) { previous. Node = previous. Node. get. Next(); } // Make second-to-last the last node previous. Node. set. Next(null); last = previous. Node; } } num. Nodes--; // Return the value of the removed node. return node. get. Item(); Programming and Problem Solving With Java 17
Writing List Classes: Char. List ²empty(), count(), to. String() // empty: Returns true if the list is empty public boolean empty() { return first == null; } // count: Returns the number of elements in the list public int count() { return num. Nodes; } // to. String: Returns a string representing the contents of // the list public String to. String() { Char. List. Node node = first; String result = "["; while (node != null) { result = result + node. get. Item() + " "; node = node. get. Next(); } } return result + "]"; Programming and Problem Solving With Java 18
Writing List Classes: Char. List ²Problems with the Char. List class Can’t tell if particular value in the list (without displaying the list and examining the output) Can't insert a value in the middle Can't remove a value from the middle Can't traverse the list, except to display every element Can't get a value from the list without removing it Can't change a value in the list without removing it and inserting the new value Can only store characters Programming and Problem Solving With Java 19
A General List Class ²Additional features over Char. List: Store into the middle (not just ends) Remove from middle Check whether a particular value is in the list Get values of elements inside the list Store any object -- not just characters ²To store and retrieve elements from middle of list Need way to refer to list position Will add current node marker Will have methods for moving current node marker Programming and Problem Solving With Java 20
A General List Class ²List operations append: Attach another list to end count: Return number of nodes to. String: Return String version of list’s contents find: Search for value. If in list, set the current node there get: Return value in current node go. First: Change current node to beginning go. Last: Change current node to end go. Next: Change current node to next node go. Previous: Change current node to previous node insert: Put new value after current node insert. First: Put new value at beginning Programming and Problem Solving With Java 21
A General List Class ²List operations (continued) insert. Last: Put new value at end is. Defined: Return true if current node defined empty: Return true if list empty is. First: Return true if current node is first node is. Last: Return true if current node is last node put: Change value of current node remove: Remove current node, return its value remove. First: Remove node at beginning of the list, return its value remove. Last: Remove node at end of list, and return its value Programming and Problem Solving With Java 22
A General List Class: Line Editor ²Today, most editors are full-screen Move cursor with keys or mouse Type at position of cursor ²Older style: line editor Make changes to one line at a time Must specify line to change with a command Not as easy to use as full-screen editor Much easier to write, though Programming and Problem Solving With Java 23
A General List Class: Line Editor ²Example of line editor: MS-DOS edlin C: >edlin Hello. java New file *I 1: *class Hello 2: *{ 3: * public static void main(String[] args) 4: * { 5: * System. out. println("Hello!"); 6: * } 7: *} 8: *^C Line commands *1 I *L *E C: > 1: *// Says Hello 2: * 3: *^C 1: // Says Hello 2: 3: *class Hello 4: { 5: public static void main(String[] args) 6: { 7: System. out. println("Hello!"); 8: } 9: } Programming and Problem Solving With Java Current line (marked with *) 24
A General List Class: Line Editor ²Will use List class to make line editor Store each line in a list node ²Commands Show all lines with line numbers Insert lines after a given line number Delete a line Quit the program ²To insert lines Type as many lines as desired Type just period on line to end Programming and Problem Solving With Java 25
A General List Class: Line Editor ²Example run of line editor +--- Edit Menu --| s) Show all lines i) Insert lines d) Delete a line | q) Quit | Enter selection: i (Enter just a period to stop inserting lines) : This is the first line in the editor. The : editor is in insert mode. When a period is : typed by itself, insert mode stops. : . +--- Edit Menu --| s) Show all lines i) Insert lines d) Delete a line | q) Quit | Enter selection: s 1: This is the first line in the editor. The 2: editor is in insert mode. When a period is 3: typed by itself, insert mode stops. +--- Edit Menu --| s) Show all lines i) Insert lines d) Delete a line | q) Quit | Enter selection: i After which line: 2 (Enter just a period to stop inserting lines) : --- This is the new third line. --: . Programming and Problem Solving With Java 26
A General List Class: Line Editor ²Example run of line editor (continued) +--- Edit Menu --| s) Show all lines i) Insert lines d) Delete a line | q) Quit | Enter selection: s 1: This is the first line in the editor. The 2: editor is in insert mode. When a period is 3: --- This is the new third line. --4: typed by itself, insert mode stops. +--- Edit Menu --| s) Show all lines | q) Quit | Enter selection: d Line to delete: 3 i) Insert lines d) Delete a line +--- Edit Menu --| s) Show all lines i) Insert lines d) Delete a line | q) Quit | Enter selection: s 1: This is the first line in the editor. The 2: editor is in insert mode. When a period is 3: typed by itself, insert mode stops. +--- Edit Menu --| s) Show all lines i) Insert lines | q) Quit | Enter selection: q Are you sure you want to quit? (y/n): y Programming and Problem Solving With Java d) Delete a line 27
A General List Class: Line Editor ²Design of the line editor program Will use the Text. Menu framework for menus Will use the List class to store lines Programming and Problem Solving With Java 28
A General List Class: Line Editor ²Methods in Edit. Application class Edit. Application(): Constructor, initializes menu handle. Event(): Event dispatcher go. To. Line(): Changes current line to user-specified line number insert. Lines(): Prompts user for a line number, then prompts user for lines to insert after that. Stops when user enters line with just a period. delete. Line(): Prompts user for a line number, then deletes that line display. Lines(): Display all lines Programming and Problem Solving With Java 29
A General List Class: Line Editor ²Edit. Application constructor // Constructor - set up menu for the editor public Edit. Application() { super("Edit Menu"); edit. Buffer = new List(); add. Selection("Show all lines", 's', SHOW_COMMAND); add. Selection("Insert lines", 'i', INSERT_COMMAND); add. Selection("Delete a line", 'd', DELETE_COMMAND); add. Selection("Quit", 'q', Text. Menu. QUIT); } ²Edit. Application constants static final int SHOW_COMMAND = 1; static final int INSERT_COMMAND = 2; static final int DELETE_COMMAND = 3; ²Edit. Application main() public static void main(String[] args) throws java. io. IOException { Edit. Application editor = new Edit. Application(); } editor. run(); Programming and Problem Solving With Java 30
A General List Class: Line Editor ²Edit. Application handle. Event() // Event dispatcher for the editor public int handle. Event(int event) throws java. io. IOException { switch (event) { case SHOW_COMMAND: display. Lines(); break; case INSERT_COMMAND: insert. Lines(); break; case DELETE_COMMAND: delete. Line(); break; case Text. Menu. QUIT: if (Keyboard. read. Char( "Are you sure you want to quit? (y/n)", "yn") != 'y') { event = Text. Menu. CANCEL_QUIT; } break; } return event; } Programming and Problem Solving With Java 31
A General List Class: Line Editor ²Edit. Application insert. Lines() steps Ask the user where to begin inserting new lines. Move to that line in the list. Read a line from the user. As long as the line isn't just a period, do the following steps. • Insert the line into the list. • Move to the new line, so the next line will be inserted after it. • Read the next line from the user. Programming and Problem Solving With Java 32
A General List Class: Line Editor ²Edit. Application insert. Lines()line number, then prompts // insert. Lines: Prompts user for a // user for lines to insert after that line. // Stops when the user enters a line with just // a period on it. void insert. Lines() throws java. io. IOException { String line; if (!edit. Buffer. empty()) { go. To. Line(Keyboard. read. Int("After which line: ", 1, edit. Buffer. count())); } } System. out. println( "(Enter just a period to stop inserting lines)"); line = Keyboard. read. String(": "); while (!line. equals(". ")) { if (edit. Buffer. is. Defined()) { edit. Buffer. insert(line); edit. Buffer. go. Next(); } else { edit. Buffer. insert. First(line); edit. Buffer. go. First(); } line = Keyboard. read. String(": "); } Programming and Problem Solving With Java 33
A General List Class: Line Editor ²Edit. Application goto. Line() // go. To. Line: Changes the current line to a specific line number // Note: line. Num must be in the range 1 to number of lines // in buffer void go. To. Line(int line. Num) { // Check precondition Debug. assert(line. Num >= 1 && line. Num <= edit. Buffer. count(), "Edit. Application. go. To. Line(): Invalid line number"); } edit. Buffer. go. First(); for(int i = 1; i < line. Num; i++) { edit. Buffer. go. Next(); } Programming and Problem Solving With Java 34
A General List Class: Line Editor ²Edit. Application delete. Line() steps Ask the user which line to delete Move to that line Delete that line ²Edit. Application delete. Line() // delete. Line: Prompts user for a line number, then deletes // that line void delete. Line() throws java. io. IOException { if (edit. Buffer. empty()) { System. out. println("No lines"); } else { go. To. Line(Keyboard. read. Int("Line to delete: ", 1, edit. Buffer. count())); edit. Buffer. remove(); } } Programming and Problem Solving With Java 35
A General List Class: Line Editor ²Edit. Application display. Lines() // display. Lines: Display all lines in the buffer void display. Lines() { int line. Number = 0; } for(edit. Buffer. go. First(); edit. Buffer. is. Defined(); edit. Buffer. go. Next()) { line. Number++; System. out. println(line. Number + ": " + edit. Buffer. get()); } ²Shows how to use for statement to traverse elements of a list Move to first line with go. First() Test whether past end of list with is. Defined() Move to next line with go. Next() Programming and Problem Solving With Java 36
A General List Class: Implementation ²List is a container type Holds elements of another type ²Array is another container type ²Common implementation of a container as a linked type Class for each node of the container Class for the container itself ²Used this implementation with Char. List. Node Char. List ²Will store an Object value in each node Programming and Problem Solving With Java 37
A General List Class: Implementation ²List. Node class List. Node { // Constructor List. Node(Object item, List. Node next) { set. Item(item); set. Next(next); } // get. Item: Returns the item value public Object get. Item() { return item; } // get. Next: Returns the next item public List. Node get. Next() { return next; } // set. Item: Sets the item to the given value public void set. Item(Object item) { this. item = item; } // set. Next: Sets the next item to the given object public void set. Next(List. Node next) { this. next = next; } // Instance variables Object item; List. Node next; Programming} Problem Solving With Java and 38
A General List Class: Implementation ²List class structure ²Instance variables // Instance variables int num. Nodes; List. Node first, last, current. Node; Programming and Problem Solving With Java // // The number of nodes in the list Reference to the first node Reference to the last node Reference to the current node 39
A General List Class: Implementation ²List constructor // Default constructor public List() { first = null; last = null; current. Node = null; num. Nodes = 0; } ²List insert. First (similar to Char. List) // insert. First: Inserts a new item at the beginning of the list. public void insert. First(Object item) { List. Node new. Node = new List. Node(item, first); } num. Nodes++; first = new. Node; if (last == null) { // Special case: An empty list. // This new node is the last node in the list. last = new. Node; } Programming and Problem Solving With Java 40
A General List Class: Implementation ²List insert. Last (similar to Char. List) // insert. Last: Inserts a new item at the end of the list public void insert. Last(Object item) { List. Node new. Node = new List. Node(item, null); } num. Nodes++; if (first == null) { // Special case: this node is the first node in // the list. first = new. Node; } else { // General case: this is not the only node in the list. // Make the last node point to this one and make // this the new last node. last. set. Next(new. Node); } last = new. Node; Programming and Problem Solving With Java 41
A General List Class: Implementation ²List insert() Puts new node after current. Node Caller responsible for setting current. Node first // insert: Inserts a new item after a node pointed to by // current. Node. // Note: current. Node must be defined public void insert(Object item) { Debug. assert(is. Defined(), "List. insert(): current. Node undefined"); List. Node new. Node = new List. Node(item, current. Node. get. Next()); } num. Nodes++; current. Node. set. Next(new. Node); if (current. Node == last) { // Special case: this is the new last node. last = new. Node; } Programming and Problem Solving With Java 42
A General List Class: Implementation ²List put() // put: Changes the value of the current. Node node to item // Note: current. Node must be defined public void put(Object item) { Debug. assert(is. Defined(), "List. put(): current. Node undefined"); current. Node. set. Item(item); } ²List get() // get: Returns the value in the current. Node // Note: current. Node must be defined public Object get() { Debug. assert(is. Defined(), "List. get(): current. Node undefined"); return current. Node. get. Item(); } Programming and Problem Solving With Java 43
A General List Class: Implementation ²List remove. First() Uses remove. Node() helper method // remove. First: Remove the first element from the list and // return its value. If item is current. Node, // then sets current. Node to next node, // unless deleting the last node. In that case, // sets current. Node to previous node. // Note: The list must not be empty public Object remove. First() { Debug. assert(!empty(), "List. remove. First(): List is empty"); } Object return. Value = first. get. Item(); remove. Node(first, null); return. Value; Programming and Problem Solving With Java 44
A General List Class: Implementation ²List remove. Last() Uses remove. Node() helper method // remove. Last: Remove the last element from the list // and return its value. If item is // current. Node, then sets current. Node // to next node, unless deleting the last // node. In that case, sets current. Node to // previous node. // Note: The list must not be empty public Object remove. Last() { Debug. assert(!empty(), "List. remove. Last(): List is empty"); } // Set last to node before last one Object return. Value = last. get. Item(); remove. Node(last, find. Previous. Node(last)); return. Value; Programming and Problem Solving With Java 45
A General List Class: Implementation ²List remove() // remove: Removes item referenced by current. Node, and // returns its value. Sets current. Node to next // node, unless deleting the last node. In that // case, sets current. Node to previous node. // Note: current. Node must be defined public Object remove() { Debug. assert(is. Defined(), "List. remove(): current. Node undefined"); Object return. Value = current. Node. get. Item(); remove. Node(current. Node, find. Previous. Node(current. Node)); return. Value; } ²List append() // append: Appends elements of the source list to this one public void append(List source) { for (source. go. First(); source. is. Defined(); source. go. Next()) { insert. Last(source. get()); } } Programming and Problem Solving With Java 46
A General List Class: Implementation ²List find() // find: If a particular value is in the list, sets // current. Node to that node and returns true. // Otherwise, leaves current. Node as it was and // returns false. public boolean find(Object data) { List. Node node = first; // Find node containing the data value while (node != null && !(node. get. Item(). equals(data))) { node = node. get. Next(); } } if (node == null) { return false; } current. Node = node; return true; Programming and Problem Solving With Java 47
A General List Class: Implementation ²List go. First() // go. First: Sets current. Node to beginning of list public void go. First() { current. Node = first; } ²List go. List() // go. Last: Sets current. Node to end of list public void go. Last() { current. Node = last; } ²List go. Next() // go. Next: Sets current. Node to next element in the list // Note: current. Node must be defined public void go. Next() { Debug. assert(is. Defined(), "List. go. Next(): current. Node undefined"); current. Node = current. Node. get. Next(); } Programming and Problem Solving With Java 48
A General List Class: Implementation ²List go. Previous() // go. Previous: Sets current. Node to previous element in // the list // Note: current. Node must be defined public void go. Previous() { Debug. assert(is. Defined(), "List. go. Previous(): current. Node undefined"); current. Node = find. Previous. Node(current. Node); } Programming and Problem Solving With Java 49
A General List Class: Implementation ²Removing a node Programming and Problem Solving With Java 50
A General List Class: Implementation ²List remove. Node() the given node from the list, adjusts // remove. Node: Removes // first, last, and current. Node // if necessary. If node is current. Node, // then sets current. Node to next node, // unless deleting the last node. In that // case, sets current. Node to previous node. void remove. Node(List. Node node, List. Node previous. Node) { if (node == first) { first = first. get. Next(); } else { previous. Node. set. Next(node. get. Next()); } if (last == node) { last = previous. Node; } // Reset current. Node, if necessary if (current. Node == node) { if (current. Node. next == null) { current. Node = previous. Node; } else { current. Node = current. Node. get. Next(); } } num. Nodes--; Programming} Problem Solving With Java and 51
A General List Class: Implementation ²List find. Previous. Node() Modified linear search Must find the node before the one we want // find. Previous. Node: Returns the node before the given // node, or null if the node is the // first node in the list. // Pre: node must be a valid node in the list List. Node find. Previous. Node(List. Node node) { List. Node previous. Node; if (node == first) { return null; } } previous. Node = first; while (previous. Node. get. Next() != node) { previous. Node = previous. Node. get. Next(); } return previous. Node; Programming and Problem Solving With Java 52
Infinite Precision Arithmetic ²Range of long may not be enough -9, 223, 372, 036, 854, 775, 808 9, 223, 372, 036, 854, 775, 807 ²Can Sample use of the that holds any number of digits make a type Infinite. Precision class. // import Infinite. Precision; public class Test. Infinite. Precision { public static void main(String[] args) { Infinite. Precision first = new Infinite. Precision( "4958614030582059703402389481948372634758695783"); Infinite. Precision second = new Infinite. Precision( "8089614672364869790583723648597007904201129034"); } } System. out. println("The sum of: System. out. println(" and: System. out. println(" is: The sum of: and: is: Programming and Problem Solving With Java " + first); " + second); " + first. add(second)); 4958614030582059703402389481948372634758695783 8089614672364869790583723648597007904201129034 13048228702946929493986113130545380538959824817 53
Infinite Precision Arithmetic ²Infinite. Precision instance variable // Instance variables List digits = new List(); ²Infinite. Precision default constructor Use this when we want to assign 0 to the number // Default Constructor // Note: An empty list is treated as zero public Infinite. Precision() { } Programming and Problem Solving With Java 54
Infinite Precision Arithmetic ²Infinite. Precision constructor with long argument // Constructor: Sets the number to that given in the // long integer public Infinite. Precision(long number) { // Put digits in number from right to left while (number != 0) { digits. insert. First(new Integer((int) (number % 10))); number = number / 10; } } Trace on new Infnite. Precision(12345); Programming and Problem Solving With Java 55
Infinite Precision Arithmetic ²Infinite. Precision constructor that given in the string with string argument // Constructor: Sets the number to // Note: The string should have only digits public Infinite. Precision(String number) { int i = 0; } while (i < number. length()) { Debug. assert(Character. is. Digit(number. char. At(i)), "Infinite. Precision(): invalid character in string"); digits. insert. Last( new Integer(Character. digit(number. char. At(i), 10))); i++; } Trace on new Infnite. Precision(“ 12345”); Programming and Problem Solving With Java 56
Infinite Precision Arithmetic ²Adding two infinite precision numbers Use the manual technique from right to left Programming and Problem Solving With Java 57
Infinite Precision Arithmetic ²Infinite. Precision add() (part 1) // add: Returns sum of this value and the other // Infinite. Precision value Infinite. Precision add(Infinite. Precision other. Value) { Infinite. Precision result = new Infinite. Precision(); int carry = 0; digits. go. Last(); other. Value. digits. go. Last(); // Add digits from right to left while (digits. is. Defined() && other. Value. digits. is. Defined()) { result. digits. insert. First(new Integer( (((Integer) digits. get()). int. Value() + ((Integer) other. Value. digits. get()). int. Value() + carry) % 10)); carry = (((Integer) digits. get()). int. Value() + ((Integer) other. Value. digits. get()). int. Value() + carry) / 10; } digits. go. Previous(); other. Value. digits. go. Previous(); Programming and Problem Solving With Java 58
Infinite Precision Arithmetic ²Infinite. Precision add()digits from this value to result's (part 2) // Append any remaining // left for (; digits. is. Defined(); digits. go. Previous()) { result. digits. insert. First(new Integer( (((Integer) digits. get()). int. Value() + carry) % 10)); carry = (((Integer) digits. get()). int. Value() + carry) / 10; } // Append any remaining digits from other value to result's // left for (; other. Value. digits. is. Defined(); other. Value. digits. go. Previous()) { result. digits. insert. First(new Integer( (((Integer) other. Value. digits. get()). int. Value() + carry) % 10)); carry = (((Integer) other. Value. digits. get()). int. Value() + carry) / 10; } if (carry != 0) { result. digits. insert. First(new Integer(carry)); } } return result; Programming and Problem Solving With Java 59
Infinite Precision Arithmetic ²Infinite. Precision to. String() // to. String: Returns a String version of the number public String to. String() { String result = ""; if (digits. empty()) { return "0"; } else { } } for (digits. go. First(); digits. is. Defined(); digits. go. Next()) { result = result + digits. get(); } return result; Programming and Problem Solving With Java 60
Making List work with Primitives ²Can store objects in a List directly List my. List = new List(); my. List. insert. First(“a string”); ²Must wrap primitives my. List. insert. First(new Integer(1234)); my. List. insert. Last(new Double(6. 39)); ²Can overload List methods so they work with primitives // insert. First: Inserts a new int at the beginning of the // list (Overloaded version for int) public void insert. First(int item) { insert. First(new Integer(item)); } Now can store integers directly my. List. insert. First(1234); Should also overload for other primitives (long, float, . . . ) Programming and Problem Solving With Java 61
Making List work with Primitives ²Must cast values from a list, and unwrap primitives String a. String = (String) my. List. get(); int an. Int = ((Integer) my. List. get()). int. Value(); ²Unfortunately, can’t override get() to return int Overriding works only when parameters differ ²To retrieve primitives from List easily Write get. Int() for retrieving integers, get. Double() for doubles, etc. // get. Int: Returns the int value in the current. Node // (Overloaded version for int) // Note: current. Node must be defined public int get. Int() { return ((Integer) get()). int. Value(); } This is why Keyboard class has read. Int(), read. String(), . . . Use of get. Int() is more readable than get() int an. Int = my. List. get. Int(); Programming and Problem Solving With Java 62
Sorting a List ²Two ways to sort a list Keep it sorted all the time Users can’t put elements where they want Sort only when needed More flesxible Users can put elements anywhere - can sort later if ncessary ²Problem List stores Object values Objects have no order -- how to sort them? ? Specific objects (dates, strings, . . . ) do have an order, though ²Can’t put sort() in List class Programming and Problem Solving With Java 63
Sorting a List: Comparators ²Can make a subclass of List that allows sorting ²Put responsibility for sorting in separate class ²Write a Comparator class Comparator: object that compares two other objects Tells which object is less ²Comparator compares Object values Comparator is an abstract class Why? Can’t compare Object values Use as a template for subclasses of Comparator Programming and Problem Solving With Java 64
Sorting a List: Comparators ²Comparator class public abstract class Comparator { // compare. To: returns negative number if a < b // 0 if a == b // positive number if a > b abstract public int compare. To(Object a, Object b); } ²Subclass of Comparator for comparing strings public class String. Comparator extends Comparator { // compare. To: returns negative number if a < b // 0 if a == b // positive number if a > b public int compare. To(Object a, Object b) { return ((String) a). compare. To((String) b); } } Programming and Problem Solving With Java 65
Sorting a List: Comparators ²Subclass of Comparator for comparing integers public class Integer. Comparator extends Comparator { // compare. To: returns negative number if a < b // 0 if a == b // positive number if a > b public int compare. To(Object a, Object b) { inta = ((Integer) a). int. Value(); intb = ((Integer) b). int. Value(); } } if (inta < intb) { return -1; } if (inta > intb) { return 1; } return 0; Programming and Problem Solving With Java 66
Sorting a List: Sortable. List ²Skeleton for Sortable. List class import List; import Comparator; public class Sortable. List extends List { // Constructor public Sortable. List(Comparator comparator) { this. comparator = comparator; } // // } -------------------------------Sort method can go here. It should use comparator. compare. To() to compare elements of the list. -------------------------------- // Instance variables Comparator comparator; Inherits all the methods of List: insert(), remove(), . . . Can use any sorting algorithm in Sortable. List Programming and Problem Solving With Java 67
Sorting a List: Quick Sort ²Quick sort Very fast and efficient On average, the fastest known sorting algorithm Can be very slow occasionally Works well with lists (and arrays) Programming and Problem Solving With Java 68
Quick Sort ² How quick sort works Choose pivot Make list of elements less than pivot Make list of elements greater than pivot Sort both lists (using quick sort) Combine the sorted lists Programming and Problem Solving With Java 69
Quick Sort ²Choice of pivot is critical in quick sort Ideally, the pivot should be the middle value of the list If list is already sorted, choosing first element gives very slow sort (why? ) ²Common pivot selection technique for array Choose middle value of: array[0] array[array. length-1] array[array. length / 2] Even better: choose random element as the pivot ²Can’t get middle element from list (efficiently) Ideas for choosing a pivot value for a list? ? Programming and Problem Solving With Java 70
Sortable. List quick. Sort() // quick. Sort: Sorts the list public void quick. Sort() { Sortable. List less. List = new Sortable. List(comparator); Sortable. List greater. List = new Sortable. List(comparator); Object pivot, element; go. First(); if (!is. Empty()) { pivot = remove. First(); while (!is. Empty()) { element = remove. First(); if (comparator. compare. To(element, pivot) < 0) { less. List. insert. First(element); } else { greater. List. insert. First(element); } } less. List. quick. Sort(); greater. List. quick. Sort(); } } // Append lists to get result append(less. List); insert. Last(pivot); append(greater. List); Programming and Problem Solving With Java 71
Sortable. List quick. Sort() ²Demonstrationthe use of the Sortable. List class, of Sortable. List // Demonstrates // which contains a quick sort algorithm. import Sortable. List; import String. Comparator; public class Test. Sortable. List { public static void main(String[] args) { Sortable. List my. List = new Sortable. List(new String. Comparator()); my. List. insert. First("banana"); my. List. insert. First("orange"); my. List. insert. First("apple"); my. List. insert. First("grape"); my. List. insert. First("pear"); my. List. insert. First("strawberry"); my. List. insert. First("cherry"); } } System. out. println("Before sort: " + my. List); my. List. quick. Sort(); System. out. println("After sort: " + my. List); Before sort: [cherry strawberry pear grape apple orange banana ] After sort: [apple banana cherry grape orange pear strawberry ] Programming and Problem Solving With Java 72
Sortable. List quick. Sort() ²Another Demonstration of Sortable. List // Demonstrates the use of the Sortable. List class, // which contains a quick sort algorithm. import Sortable. List; import Integer. Comparator; public class Test. Sortable. List 2 { public static void main(String[] args) { Sortable. List my. List = new Sortable. List(new Integer. Comparator()); my. List. insert. First(3); my. List. insert. First(8); my. List. insert. First(2); my. List. insert. First(1); my. List. insert. First(4); my. List. insert. First(7); my. List. insert. First(5); } } // Note use of special insert. First() // made especially for int type // (Otherwise, would need to use // new Integer(3), for example, // instead of 3) System. out. println("Before sort: " + my. List); my. List. quick. Sort(); System. out. println("After sort: " + my. List); Before sort: [5 7 4 1 2 8 3 ] After sort: [1 2 3 4 5 7 8 ] Programming and Problem Solving With Java 73
A Set Type ²Set: heterogeneous, unordered collection of elements without duplicate values ²Common set operations Programming and Problem Solving With Java 74
A Set Type ²Set operations Programming and Problem Solving With Java 75
A Set Type ²Demonstrationuse of the Set class of how to use // Demonstrates import Set; public class Test. Set { public static void main(String[] args) { // Make two sets Set a = new Set(); Set b = new Set(); Set a is Set b is a union b is a intersect b is a difference b is // Put 1 and 2 in set a a. add("1"); a. add("2"); // Put 2 and 3 in set b b. add("2"); b. add("3"); } } // Display results System. out. println("Set a is System. out. println("Set b is System. out. println("a union b is System. out. println("a intersect b is System. out. println("a difference b is Programming and Problem Solving With Java " " " + + + {2 1} {3 2} {1} a); b); a. union(b)); a. intersect(b)); a. difference(b)); 76
A Set Type: Implementation ²Store set elements in a list // Instance variables List data = new List(); ²Constructor for Set // Default constructor public Set() { } ²add() method must not insert duplicate values // add: Adds an element to a set if not already in the set. // If the element is already in the set, it is not // added again. public void add(Object item) { if (!is. Member(item)) { data. insert. First(item); } } Programming and Problem Solving With Java 77
A Set Type: Implementation ²Set remove() method // remove: Removes the given item from the set. Does nothing // if the element is not in the set. public void remove(Object item) { if (data. find(item)) { data. remove(); } } Easy to write List class methods do all the work Programming and Problem Solving With Java 78
A Set Type: Implementation ²Set union() method // union: Returns the union of this set and other. Set, that // is, all items in either set. public Set union(Set other. Set) { Set result = new Set(); // Copy everything from other. Set to result. data. append(other. Set. data); // Add items from this set to the result (The add() member // method will make sure that no element is added twice. ) for (data. go. First(); data. is. Defined(); data. go. Next()) { result. add(data. get()); } } return result; ²Another approach: use add() for both sets Not as efficient - don’t need to check for duplicates until second set added Programming and Problem Solving With Java 79
A Set Type: Implementation ²Set intersect() method // intersect: Returns the intersection of this set and // other. Set, that is, all items in both sets. public Set intersect(Set other. Set) { Set result = new Set(); } // Copy items from this set that are also in other. Set to // result for (data. go. First(); data. is. Defined(); data. go. Next()) { if (other. Set. is. Member(data. get())) { result. add(data. get()); } } return result; Programming and Problem Solving With Java 80
A Set Type: Implementation ²Set difference() method // difference: Returns the difference of this set and // other. Set, that is, all items in this set but // not in other. Set. public Set difference(Set other. Set) { Set result = new Set(); // Copy those items from this set that are not in other. Set // to result for (data. go. First(); data. is. Defined(); data. go. Next()) { if (!other. Set. is. Member(data. get())) { result. add(data. get()); } } } return result; Programming and Problem Solving With Java 81
A Set Type: Implementation ²Set to. String() method // to. String: Returns the set's contents as a string in // standard displayable format: {1, 3, 2} public String to. String() { String list. Str = data. to. String(); } return "{" + list. Str. substring(1, list. Str. length() - 2) + "}"; Programming and Problem Solving With Java 82
A Set Type: Implementation ²Set count(), empty(), is. Full(), is. Member() methods // count: Returns the number of items in the set public int count() { return data. count(); } // empty: Returns true if the set is empty, false // otherwise public boolean empty() { return data. empty(); } // is. Full: Returns true if the set is not empty, false // otherwise (always return false for list // implemention) public boolean is. Full() { return false; } // is. Member: Returns true if item is in the set, false // otherwise boolean is. Member(Object item) { return data. find(item); } Programming and Problem Solving With Java 83
Doubly Linked Lists ²Singly linked list Each node references its successor Can only move from node to next node ²Doubly linked list Each node references successor and predecessor Advantage: Can delete node without searching for successor and predecessor Advantage: Can go through list backward Programming and Problem Solving With Java 84
Doubly Linked Lists ²Problems with doubly linked lists Takes more memory than singly linked Lots of special cases in implementation ²Can remove many special cases with Dummy header: unused node Circular references Programming and Problem Solving With Java 85
Doubly Linked Lists ²Empty doubly linked list ²Note: reference to end of list not necessary Programming and Problem Solving With Java 86
Doubly Linked List: Implementation ²Double. List. Node class Double. List. Node { // Default Constructor public Double. List. Node() { this(null, null); // (This is the default action, but it // doesn't hurt to be explicit) } // Constructor public Double. List. Node(Object item, Double. List. Node previous, Double. List. Node next) { this. item = item; this. previous = previous; this. next = next; } // get. Item: Returns the item value public Object get. Item() { return item; } // get. Next: Returns the next item public Double. List. Node get. Next() { return next; } Programming and Problem Solving With Java 87
Doubly Linked List: Implementation ²Double. List. Node class (continued) // get. Previous: Returns the previous item public Double. List. Node get. Previous() { return previous; } // set. Item: Sets the item to the given value public void set. Item(Object item) { this. item = item; } // set. Next: Sets the next item to the given object public void set. Next(Double. List. Node next) { this. next = next; } // set. Previous: Sets the previous item to the given object public void set. Previous(Double. List. Node previous) { this. previous = previous; } } // Instance variables Double. List. Node next, previous; Object item; Programming and Problem Solving With Java 88
Doubly Linked List: Implementation ²Double. List instance variables // Instance variables Double. List. Node header; Double. List. Node current. Node; int num. Nodes; ²Double. List constructor // Reference to dummy header // Reference to current node // Number of nodes in list // Default constructor public Double. List() { num. Nodes = 0; } // Allocate dummy header node header = new Double. List. Node(); header. set. Previous(header); header. set. Next(header); Programming and Problem Solving With Java 89
Doubly Linked List: Implementation ²Inserting a node at the beginning of a list Programming and Problem Solving With Java 90
Doubly Linked List: Implementation ²Double. List insert() method // insert. First: Inserts a new item at the beginning of the // list public void insert. First(Object item) { Double. List. Node old. First. Node = header. get. Next(); Double. List. Node new. Node = new Double. List. Node(item, header, old. First. Node); } num. Nodes++; old. First. Node. set. Previous(new. Node); header. set. Next(new. Node); Programming and Problem Solving With Java 91
Doubly Linked List: Implementation ²Removing a value from a list Programming and Problem Solving With Java 92
Doubly Linked List: Implementation ²Double. List remove() // remove: Removes item referenced by current. Node, and // returns its value. Sets current. Node to next // node, unless deleting the last node. In that // case, sets current. Node to previous node. // Note: current. Node must be defined public Object remove() { Debug. assert(is. Defined(), "Double. List. remove(): current. Node undefined"); Object return. Value = current. Node. get. Item(); remove. Node(current. Node); return. Value; } Programming and Problem Solving With Java 93
Doubly Linked List: Implementation ²Double. List remove. Node() node from the list, adjusts // remove. Node: Removes the given // first, last, and current. Node // if necessary. If node is current. Node, // then sets current. Node to next node, // unless deleting the last node. In that // case, sets current. Node to previous node. void remove. Node(Double. List. Node node) { Double. List. Node next. Node = node. get. Next(), previous. Node = node. get. Previous(); previous. Node. set. Next(next. Node); next. Node. set. Previous(previous. Node); num. Nodes--; } // Reset current. Node, if necessary if (current. Node == node) { if (current. Node. next == header) { current. Node = previous. Node; } else { current. Node = next. Node; } } Programming and Problem Solving With Java 94
Doubly Linked List: Implementation ²Double. List find() // find: If a particular value is in the list, sets // current. Node to that node and returns true. // Otherwise, leaves current. Node as it was and // returns false. public boolean find(Object data) { Double. List. Node node = header. get. Next(); // Find node containing the data value while (node != header && !(node. get. Item(). equals(data))) { node = node. get. Next(); } } if (node == header) { return false; } current. Node = node; return true; Programming and Problem Solving With Java 95
Computer Security: Layers ²Layers of security Programming and Problem Solving With Java 96
Computer Security: Layers ²Physical security: intrusion prevention and detection Fences Lack of windows Walls that extend to the roof Mechanical and electronic locks Guards Adequate lighting Automated entry booths Uninterruptible power supplies Power filters and surge suppressors Smoke and fire detection Automatic fire extinguishers Programming and Problem Solving With Java 97
Computer Security: Layers ²Operating system Identification: unique name for each user Authentication: confirmation of user by computer and vice versa ²Authentication techniques Check what user knows (password, . . . ) Check what user carries (smartcard, . . . ) Check who user is (retina scan, voice print, . . . ) ²Password recommendations (US Do. D) Users should be able to change Should be machine generated System should display last login time Programming and Problem Solving With Java 98
Computer Security: Disclosure ²Disclosure of information can be harmful Military and government disclosure: national security Commercial disclosure: trade secrets, customer lists, . . . ²US Laws forbidding disclosure of personal information Right to Financial Privacy (1978) Privacy Act (1974) (Other countries have similar laws) Programming and Problem Solving With Java 99
Computer Security: Disclosure ² Covert channel Unconventional method of information transfer ² Types of covert channels Storage Timing ² Very difficult to identify covert channels Programming and Problem Solving With Java 100
Computer Security: Disclosure ²Indirect disclosure: inference or aggregation ²Inference Can guess value by adding outside information Example: Anderson is only female manager Can guess Anderson’s salary from FSalary - TSalary • FSalary, total salary of all females • TSalary, total salary of all non-manager females ²Aggregation Can guess value by combining nonsensitive values Example: knowing 1 CIA phone number is Ok Knowing ALL CIA phone numbers is NOT Ok Programming and Problem Solving With Java 101
Computer Security: Modification ²Data modification or destruction more serious to commercial computers Usually caused by disgruntled employees ²Trapdoor: turns off normal security checking Example: no password for some accounts ²Trojan horse: malicious program hidden in another ²Virus: self-perpetuating Trojan horse, attaches to other programs ²Worm: self-perpetuating program takes over idle machines in a network ²Time bombs and logic bombs Programming and Problem Solving With Java 102
Computer Security: Military ²Focus: control of disclosure ²Sensitivity levels Unclassified Confidential Secret Top secret ²Compartments: topic areas Nuclear Spy . . . ²Each object has security level ²Each user has clearance Programming and Problem Solving With Java 103
Computer Security: Military ²Mandatory access control (MAC) Enforcement of military security Unauthorized disclosure is illegal ²Discretionary access control (DAC) Owner of data decides who can access it Most common commercial security technique Used in many operating systems (NT, Unix, VAX VMS) ²MAC and DAC combined = military security Programming and Problem Solving With Java 104
Computer Security: Military ²Modes of operation for military computers Dedicated: users cleared for all data, can access all data System-high: users cleared for all data, can access some data Compartmented: users cleared for most restricted data, can access some data Multilevel: users not cleared for all data, can access some data ²Most military computers run in system-high mode ²Military would like to move to multilevel Cheaper Easier to keep data consistent Programming and Problem Solving With Java 105
Computer Security: Military ²Do. D security classifications ²Level D No security ²Level C (C 1, C 2) Discretionary access control NT, VAX VMS, some variants of Unix are C 2 is minimum for commercial security ²Level B (B 1, B 2, B 3) Level C features Plus mandatory access control ²Level A Level B features Plus formal proof of correctness Programming and Problem Solving With Java 106
Computer Security: Access Control ²Discretionary access control (DAC) Allows data owner to choose who else can access Little protection against Trojan horse attacks ²Implementation of DAC Capabilities Access control lists Protection bits ²Capabilities System associates access rights with each user Advantage: more protection against Trojan horse attacks Disadvantage: revoking rights is difficult Programming and Problem Solving With Java 107
Computer Security: Access Control ²Access control lists Another way to implement DAC Stores list of authorized users with each resource US National Computer Center recommends this approach Programming and Problem Solving With Java 108
Computer Security: Access Control ²Protection bits Another way to implement DAC 9 bits (Boolean values) per object Owner read Owner write Owner execute Group read Group write Group execute Others read Others write Others execute Used with many Unix variants % ls -l newmodel. txt -rw-rw---- 1 slack 219 Jan 6 14: 07 newmodel. txt % chmod u-w newmodel. txt -r--rw---- 1 slack 219 Jan 6 14: 07 newmodel. txt Change projection with chmod Simplest approach to implement DAC But weak protection -- doesn’t qualify for level C security Programming and Problem Solving With Java 109
Computer Security: Commercial ²Commercial security emphasizes prevention of unauthorized modification ²Most common unauthorized modification Programming and Problem Solving With Java 110
Computer Security: Commercial ²Major types of undesirable changes Unauthorized user inserts false information deliberately Authorized user inserts false information accidentally ²Prevent unauthorized changes with security techniques MAC DAC ²How to prevent accidental changes? Programming and Problem Solving With Java 111
Computer Security: Commercial ²Can’t prevent all accidental changes ²Prevent most of them with integrity constraints (business rules) Age of employees must be between 18 and 80 No employee can earn more than his or her manager ²Integrity Validity (no false information) Completeness (all true information included) ²Integrity usually enforced at database level Correct state: when data satisfies all Integrity constraints ²Database system tries to keep data in correct state Programming and Problem Solving With Java 112
Computer Security: Commercial ²Transaction: group of changes to data Must take database from one correct state to another correct state ²Transaction example Integrity constraint: Sales + value of inventory is constant Customer buys shoes: steps in database 1. Subtract value of shoes from inventory 2. Add amount of sale to sum of today’s sales Incorrect state between steps Correct state only after both steps completed Programming and Problem Solving With Java 113
Computer Security: Commercial ²Types of database integrity constraints Structure-based: part of the database structure Value-based: based on values in the database ²Structure-based example Can only store an integer in an Age field (defined as Integer) ²Value-based example No employee can earn more than his or her manager Programming and Problem Solving With Java 114
Computer Security: Commercial ²Clark-Wilson model of integrity Looks like objectoriented!! Only transaction procedures can change data Users can only use transaction procedures -- can’t access data directly Task: several transactions Separation of duties: make sure a different person handles each transaction in a task ²Example: Paying a supplier Receive new inventory Approve supplier’s invoice Request payment to supplier Print check Programming and Problem Solving With Java 115
Computer Security: Individual ²Choose a good password Shouldn’t be easy to guess Don’t use name of friend, pet, hometown, . . . Don’t use a word in English Should be easy to remember, but nonsensical to others ²How to choose a password Use a mnemonic (“The frog jumped up and kicked the horse. ” Tfjuakth) Concatenate two unrelated words (“cube” + “branch” cubebranch) ²Keep your password safe Don’t write it down anywhere Don’t let others user your account Programming and Problem Solving With Java 116
Computer Security: Individual ²Encryption Scrambles data according to an encryption key Makes data useless to others Must use decryption key to get original data back ²Encryption by rotation Plaintext: “This is a test. ” Encrypted text (key of 3): “Wklv%lv%whvw 1” ²Common encryption techniques DES Blowfish PGP Programming and Problem Solving With Java 117
Computer Security: Individual ²Protect against viruses Use virus protection programs Keep their virus lists current ²Protect against fire, flood, theft Insurance Backup ²Back up your data Copy to diskette, Zip disk, tape Full backup: all the data on the computer Incremental backup: changes since last full backup Programming and Problem Solving With Java 118
Computer Security: Individual ²Backup procedure Have at least two backups -- one offsite Programming and Problem Solving With Java 119
70720fd56cc84457b1e171cad58ed9d1.ppt