Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية.

Similar presentations


Presentation on theme: "1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية."— Presentation transcript:

1 1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية

2 Array vs. ArrayList Arrays are a simple Data Structure Arrays store a row of values of the same type: Primitive types (int, double, etc) int[] prices = new prices[10]; //This stores 10 different prices Object types (Students, Cars, etc) Students[] aitiClass= new Students[70] //Each student in the class is a separate object

3 Array vs. ArrayList Access each value in an Array using the index; int[] primeNums = new int[20]; primeNums[0] = 1; primeNums[3] = 5; Remember, Array indices start at 0. What was the main problem with Arrays? Array lengths could not be changed once declared. Arrays can be annoying to use due to their fixed length. We need something with a similar structure to that of Arrays, but which can be resized automatically (no more fixed length issues). We use the ArrayListClass!!!

4 Array vs. ArrayList In an ArrayList, the elements are stored internally as an Array. Elements in ArrayList are stored as type Object Since ArrayList is a class, it has its own methods too… They must therefore be imported by typin import java.util.*; At the top of your class

5 5 ArrayList methods add( value ) appends value at end of list add( index, value ) inserts given value at given index, shifting subsequent values right clear() removes all elements of the list indexOf( value ) returns first index where given value is found in list (-1 if not found) get( index ) returns the value at given index remove( index ) removes/returns value at given index, shifting subsequent values left set( index, value ) replaces value at given index with given value size() returns the number of elements in list toString() returns a string representation of the list such as "[3, 42, -7, 15]" Which operations are most/least efficient, and why?

6 6 Example of using ArrayList 01import java.util.*; 02 03public class ArrayListExamples { 04 05 public static void main(String args[]) { 06 // Creating an empty array list 07 ArrayList list = new ArrayList (); 08 09 // Adding items to arrayList 10 list.add("Item1"); 11 list.add("Item2"); 12 list.add(2, "Item3"); // it will add Item3 to the third position of array list 14 list.add("Item4"); 15 16 // Display the contents of the array list 17 System.out.println("The arraylist contains the following elements: “+ list); 19 20 // Checking index of an item 21 int pos = list.indexOf("Item2"); 22 System.out.println("The index of Item2 is: " + pos); 23 24 // Checking if array list is empty 25 boolean check = list.isEmpty(); 26 System.out.println("Checking if the arraylist is empty: " + check); 27

7 7 Example of using ArrayList 28 // Getting the size of the list 29 int size = list.size(); 30 System.out.println("The size of the list is: " + size); 31 32 // Checking if an element is included to the list 33 boolean element = list.contains("Item5"); 34 System.out.println("Checking if the arraylist contains the object Item5: “+ element); 37 38 // Getting the element in a specific position 39 String item = list.get(0); 40 System.out.println("The item is the index 0 is: " + item); 41 42 // Retrieve elements from the arraylist 43 44 // 1st way: loop using index and size list 45 System.out.println("Retrieving items with loop using index and size list"); 47 for (int i = 0; i < list.size(); i++) { 48 System.out.println("Index: " + i + " - Item: " + list.get(i)); 49 } 50 51 // 2nd way:using foreach loop 52 System.out.println("Retrieving items using foreach loop"); 53 for (String str : list) { 54 System.out.println("Item is: " + str); 55 } 56 57 // 3rd way:using iterator 58 // hasNext(): returns true if there are more elements 59 // next(): returns the next element 60 System.out.println("Retrieving items using iterator"); 61 for (Iterator it = list.iterator(); it.hasNext();) { 62 System.out.println("Item is: " + it.next()); 63 } 64 65 // Replacing an element 66 list.set(1, "NewItem"); 67 System.out.println("The arraylist after the replacement is: " + list); 68 69 // Removing items 70 // removing the item in index 0 71 list.remove(0); 72 73 // removing the first occurrence of item "Item3" 74 list.remove("Item3"); 75 76 System.out.println("The final contents of the arraylist are: " + list); 77 78 // Converting ArrayList to Array 79 String[] simpleArray = list.toArray(new String[list.size()]); 80 System.out.println("The array created after the conversion of our arraylist is: " 81 + Arrays.toString(simpleArray)); 82 } 83}

8 8 Example of using ArrayList 57 // 3rd way:using iterator 58 // hasNext(): returns true if there are more elements 59 // next(): returns the next element 60 System.out.println("Retrieving items using iterator"); 61 for (Iterator it = list.iterator(); it.hasNext();) { 62 System.out.println("Item is: " + it.next()); 63 } 64 65 // Replacing an element 66 list.set(1, "NewItem"); 67 System.out.println("The arraylist after the replacement is: " + list); 68 69 // Removing items // removing the item in index 0 71 list.remove(0); 72 73 // removing the first occurrence of item "Item3" 74 list.remove("Item3"); 75 76 System.out.println("The final contents of the arraylist are: " + list); 77 78 // Converting ArrayList to Array 79 String[] simpleArray = list.toArray(new String[list.size()]); 80 System.out.println("The array created after the conversion of our arraylist is: " 81 + Arrays.toString(simpleArray)); 82 } 83}

9 9 ArrayList vs. LinkedList java.util.ArrayList java.util.LinkedList ArrayList LinkedList

10 10 ArrayList vs. LinkedList In a linked list, each link stores an item and is connected to the next link The list holds a reference to the first element A LinkedList stores its elements internally in a linked list data structure LinkedList SecondList = new LinkedList();

11 11 ArrayList vs. LinkedList An array stores a sequence of values type [] anArray = new type [ capacity ]; Drawback: –capacity of array fixed –must know max number of values at compile time –either the program runs out of space or wastes space Solution: collection classes –capacity can grow and shrink as program runs

12 12 List Types Free List Stack: Last Input First Output Queue : First Input First Output We can create any type of list using ArrayList or LinkedList queue stack

13 13 Stacks stack: A collection based on the principle of adding elements and retrieving them in the opposite order. –Last-In, First-Out ("LIFO") –The elements are stored in order of insertion, but we do not think of them as having indexes. –The client can only add/remove/examine the last element added (the "top"). basic stack operations: –push: Add an element to the top. –pop: Remove the top element. –peek: Examine the top element.

14 14 Stacks in computer science Programming languages and compilers: –method calls are placed onto a stack (call=push, return=pop) –compilers use stacks to evaluate expressions Matching up related pairs of things: –find out whether a string is a palindrome –examine a file to see if its braces { } and other operators match –convert "infix" expressions to "postfix" or "prefix" Sophisticated algorithms: –searching through a maze with "backtracking" –many programs use an "undo stack" of previous operations method3 return var local vars parameters method2 return var local vars parameters method1 return var local vars parameters

15 15 Class Stack Stack s = new Stack (); s.push(42); s.push(-3); s.push(17); // bottom [42, -3, 17] top while(!s.isEmpty()) System.out.println(s.pop()); // print 17 -3 42 Stack () constructs a new stack with elements of type E push( value ) places given value on top of stack pop() removes top value from stack and returns it; throws EmptyStackException if stack is empty peek() returns top value from stack without removing it; throws EmptyStackException if stack is empty size() returns number of elements in stack isEmpty() returns true if stack has no elements

16 16 List Stack Example Java Code Stack s = new Stack (); s.push(6); top 6

17 17 List Stack Example top 6 1 Java Code Stack s = new Stack (); s.push(6); s.push(1);

18 18 List Stack Example top 617 Java Code Stack s = new Stack (); s.push(6); s.push(1); s.push(7);

19 19 List Stack Example top 6 1 7 8 Java Code Stack s = new Stack (); s.push(6); s.push(1); s.push(7); s.push(8);

20 20 List Stack Example Java Code... st.push(6); st.push(1); st.push(7); st.push(8); st.pop(); // before top 6178

21 21 List Stack Example Java Code... st.push(6); st.push(1); st.push(7); st.push(8); st.pop(); // after top 617

22 22 Queues queue: Retrieves elements in the order they were added. –First-In, First-Out ("FIFO") –Elements are stored in order of insertion but don't have indexes. –Client can only add to the end of the queue, and can only examine/remove the front of the queue. basic queue operations: –add (enqueue): Add an element to the back. –remove (dequeue): Remove the front element. –peek: Examine the front element.

23 23 Queues in computer science Operating systems: –queue of print jobs to send to the printer –queue of programs / processes to be run –queue of network data packets to send Programming: –modeling a line of customers or clients –storing a queue of computations to be performed in order Real world examples: –people on an escalator or waiting in a line –cars at a gas station (or on an assembly line)

24 24 Programming with Queue s Queue q = new LinkedList (); q.add(42); q.add(-3); q.add(17); // front [42, -3, 17] back while(!q.isEmpty()) System.out.println(q.remove()); // print 42 -3 17 add( value ) places given value at back of queue remove() removes value from front of queue and returns it; throws a NoSuchElementException if queue is empty peek() returns front value from queue without removing it; returns null if queue is empty size() returns number of elements in queue isEmpty() returns true if queue has no elements

25 25 Stack/queue motivation Sometimes it is good to have a collection that is less powerful, but is optimized to perform certain operations very quickly. Stacks and queues do few things, but they do them efficiently. stack queue

26 26 Algorithm Evaluating Expressions Phase 1: Scanning the expression The program scans the expression from left to right to extract operands, operators, and the parentheses. 1.1.If the extracted item is an operand, push it to operandStack. 1.2.If the extracted item is a + or - operator, process all the operators at the top of operatorStack and push the extracted operator to operatorStack. 1.3.If the extracted item is a * or / operator, process the * or / operators at the top of operatorStack and push the extracted operator to operatorStack. 1.4.If the extracted item is a ( symbol, push it to operatorStack. 1.5.If the extracted item is a ) symbol, repeatedly process the operators from the top of operatorStack until seeing the ( symbol on the stack. Phase 2: Clearing the stack Repeatedly process the operators from the top of operatorStack until operatorStack is empty.

27 27 Example


Download ppt "1 Chapter 20 Lists, Stacks, Queues Lecture 7 Dr. Musab Zghoul برمجة هيكلية."

Similar presentations


Ads by Google