This recitation 1 An interesting point about A2: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.

Slides:



Advertisements
Similar presentations
Chapter 25 Lists, Stacks, Queues, and Priority Queues
Advertisements

TK1924 Program Design & Problem Solving Session 2011/2012
JavaCUP JavaCUP (Construct Useful Parser) is a parser generator
CS Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.
Final and Abstract Classes
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Introduction to Computation and Problem
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Chapter 7. Binary Search Trees
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Programming Language Concepts
Lesson 6 CDT301 – Compiler Theory, Spring 2011 Teacher: Linus Källberg.
Lecture 15 Linked Lists part 2
1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
Chapter 17 Recursion.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Exercise Session 5.
Chapter 17 Linked Lists.
Linked Lists Chapter 4.
Data Structures ADT List
Chapter 24 Lists, Stacks, and Queues
ITEC200 Week04 Lists and the Collection Interface.
AITI Lecture 19 Linked List Adapted from MIT Course 1.00 Spring 2003 Lecture 26 and Tutorial Note 9 (Teachers: Please do not erase the above note)
Modern Programming Languages, 2nd ed.
Chapter 1 Object Oriented Programming 1. OOP revolves around the concept of an objects. Objects are created using the class definition. Programming techniques.
CSE Lecture 12 – Linked Lists …
Semantic Analysis and Symbol Tables
2007 Pearson Education, Inc. All rights reserved C Structures, Unions, Bit Manipulations and Enumerations.
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Object Oriented Programming with Java
Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign.
The List ADT Textbook Sections
Object-Oriented Programming. 2 An object, similar to a real-world object, is an entity with certain properties, and with the ability to react in certain.
A Third Look At ML 1. Outline More pattern matching Function values and anonymous functions Higher-order functions and currying Predefined higher-order.
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Chapter Three Arithmetic Expressions and Assignment Statements
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
Pointers and Arrays Chapter 12
1 Chapter 3:Operators and Expressions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2006 | Last Updated: July 2006 Slide 1 Operators and Expressions.
Chapter 14 Introduction to Collections
Introduction to Recursion and Recursive Algorithms
Abstract Class, Packages and interface from Chapter 9
1 Abstract Class and Packages from Chapter 9 Lecture.
Building Java Programs Chapter 14
Data Structures Using C++ 2E
1 Programming Languages (CS 550) Mini Language Interpreter Jeremy R. Johnson.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks.
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Topic 3 The Stack ADT.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 Stacks Chapter 4 2 Introduction Consider a program to model a switching yard –Has main line and siding –Cars may be shunted, removed at any time.
Lecture Objectives To understand how Java implements a stack To learn how to implement a stack using an underlying array or linked list Implement a simple.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
COP3530 Data Structures600 Stack Stack is one the most useful ADTs. Like list, it is a collection of data items. Supports “LIFO” (Last In First Out) discipline.
CS/ENGRD 2110 SPRING 2015 Lecture 6: Consequence of type, casting; function equals 1.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 18 Java Collections Framework
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
Generics with ArrayList and HashSet 1 ge·ner·ic adjective \jə ̇ˈ nerik, -rēk\ relating or applied to or descriptive of all members of a genus, species,
By Mr. Muhammad Pervez Akhtar
Enums and The Java Collections classes
Stacks Chapter 4.
Presentation transcript:

This recitation 1 An interesting point about A2: Using previous methods to avoid work in programming and debugging. How much time did you spend writing and debugging prepend? Enums (enumerations) Generics and Javas Collection interfaces and classes Parsing arithmetic expressions using a grammar that gives precedence to * and / over + and – (if there is time)

How to use previous methods in A2 2 The A2 handout contained this: Did you read that? Think about it? Attempt it? Further guidelines and instructions! Note that some methods that you have to write …. Also, in writing methods 4..7, writing them in terms of calls on previously written methods may save you time. A lesson in: 1.Reading carefully, wisely. 2.Thinking about what methods do, visualizing what they do.

3 head pred succ Legend … … Suppose we want to append e to this list: e This is what it looks like after the append: head e … … What if we prepended e instead of appending it?

4 head … … What append does: head e … … What prepend does: head e … … Therefore: prepend(v); can be done by append(v); head= head.pred; body of prepend

5 head e … … e … … prepend(v) is simply append(v); head= head.pred; What append does What prepend does Morals of the story: 1.Read carefully. 2.Visualize what methods do; understand specs completely. 3.Avoid duplication of effort by using previously written methods How much time did you spend writing and debug- ging prepend? Did you try to write prepend in terms of append?

About enums (enumerations) 6 An enum: a class that lets you create mnemonic names for entities instead of having to use constants like 1, 2, 3, 4 The declaration below declares a class Suit. After that, in any method, use Suit.Clubs, Suit.Diamonds, etc. as constants. public enum Suit {Clubs, Diamonds, Hearts, Spades} could be private, or any access modifier new keyword The constants of the class are Clubs, Diamonds, Hearts, Spades

public enum Suit {Clubs, Diamonds, Hearts, Spades} 7 Clubs Diamonds Hearts Spades Suit Suit Suit Suit Clubs, Diamonds, Hearts, Spades Are static variables of class enum Four static final variables that contain pointers to objects

8 Testing for an enum constant 8 public enum Suit {Clubs, Diamonds, Hearts, Spades} Suit s= Suit.Clubs; Then s == Suit.Clubs is true s == Suit.Hearts is false switch(s) { case Clubs: case Spades: color= black; break; case Diamonds: case Hearts: color= red; break; } Can use a switch statement Type of s is Suit. Inside the switch, you cannot write Suit.Hearts instead of Hearts

9 Miscellaneous points about enums public enum Suit {Clubs, Diamonds, Hearts, Spades} 1. Suit is a subclass of Enum (in package java.lang) This declaration is shorthand for a class that has a constructor, four constants (public static final variables), a static method, and some other components. Here are some points: 2. It is not possible to create instances of class Suit, because its constructor is private! 3. Its as if Clubs (as well as the other three names) is declared within class Suit as public static final Suit Clubs= new Suit(some values); You dont care what values

Miscellaneous points about enums 10 public enum Suit {Clubs, Diamonds, Hearts, Spades} 4. Static function values() returns a Suit[] containing the four constants. You can, for example, use it to print all of them: for (Suit s : Suit.values()) System.out.println(s); Output: Clubs Diamonds Hearts Spades toString in object Clubs returns the string Clubs Can save this array in a static variable and use it over and over: private static Suit[] mine= Suit.values();

Miscellaneous points about enums 11 public enum Suit {Clubs, Diamonds, Hearts, Spades} 5. Static function valueOf(String name) returns the enum constant with that name: Suit c= Suit.valueOf(Hearts); After the assignment, c contains (the name of) object Hearts c Suit This is the object for Hearts:

Miscellaneous points about enums 12 public enum Suit {Clubs, Diamonds, Hearts, Spades} 6. Object Clubs (and the other three) has a function ordinal() that returns it position in the list This declaration is shorthand for a class that has a constructor, four constants (public static final variables), a static method, and some other components. Here are some points: We have only touched the surface of enums. E.g. in an enum declaration, you can write a private constructor, and instead of Clubs you can put a more elaborate structure. All this is outside the scope of CS2110. Suit.Clubs.ordinal() is 0 Suit.Diamonds.ordinal() is 1

13 Package java.util has a bunch of classes called the Collection Classes that make it easy to maintain sets of values, list of values, queues, and so on. You should spend some time looking at their API specifications and getting familiar with them. Remember: A set is a bunch of distinct (different) values. No ordering is implied A list is an ordered bunch of values. It may have duplicates.

14 Interface Collection: abstract methods for dealing with a group of objects (e.g. sets, lists) Abstract class AbstractCollection: overrides some abstract methods with methods to make it easier to fully implement Collection AbstractList, AbstractQueue, AbstractSet, AbstractDeque overrides some abstract methods of AbstractCollection with real methods to make it easier to fully implement lists, queues, set, and deques Next slide contains classes that you should become familiar with and use. Spend time looking at their specifications. There are also other useful Collection classes

15 Class ArrayList extends AbstractList: An object is a growable/shrinkable list of values implemented in an array Class Arrays: Has lots of static methods for dealing with arrays searching, sorting, copying, etc. Class HashSet extends AbstractSet: An object maintains a growable/shrinkable set of values using a technique called hashing. We will learn about hashing later. Class LinkedList extends AbstractSequentialList: An object maintains a list as a doubly linked list Class Stack extends Vector: An object maintains LIFO (last- in-first-out) stack of objects Class Vector extends AbstractList: An object is a growable/shrinkable list of values implemented in an array. An old class from early Java

ArrayList 16 ArrayList v= new ArrayList (); ArrayList Object defined in package java.util Fields that contain a list of objects (o 0, o 1, …, o size()-1 ) ArrayList () add(Object) get(int) size() remove(…) set(int, Object) … v Vector An object of class ArrayList contains a growable/shrinkable list of elements (of class Object). You can get the size of the list, add an object at the end, remove the last element, get element i, etc. More methods exist! Look at them!

HashSet 17 HashSet s= new HashSet(); Hashset Object Fields that contain a setof objects {o 0, o 1, …, o size()-1 } HashSet() add(Object) contains(Object) size() remove(Object) … s HashSet An object of class HashSet contains a growable/shrinkable set of elements (of class Object). You can get the size of the set, add an object to the set, remove an object, etc. More methods exist! Look at them! Dont ask what hash means. Just know that a Hash Set object maintains a set

Iterating over a HashSet or ArrayList 18 HashSet s= new HashSet(); … code to store values in the set … for (Object e : s) { System.out.println(c); } HashSet Object Fields that contain a setof objects {o 0, o 1, …, o size()-1 } HashSet() add(Object) contains(Object) size() remove(Object) … s HashSet A loop whose body is executed once with e being each element of the set. Dont know order in which set elements processed Use same sort of loop to process elements of an ArrayList in the order in which they are in the ArrayList.

Format of ArrayList object 19 ArrayList AbstractList AbstractCollection Object List Collection Iterable List Collection Iterable Collection Iterable Iterable Not discussed today Interface Collection: abstract methods for dealing with a group of objects (e.g. sets, lists) Abstract class AbstractCollection: overrides some abstract methods with real methods to make it easier to fully implement Collection ArrayList implements 3 other interfaces, not shown

Format of ArrayList object 20 Vector AbstractList AbstractCollection Object List Collection Iterable List Collection Iterable Collection Iterable Iterable Not discussed today Interface List: abstract methods for dealing with a list of objects (o 0, …, o n-1 ). Examples: arrays, Vectors Abstract class AbstractList: overrides some abstract methods with real methods to make it easier to fully implement List Homework: Look at API specifications and build diagram giving format of HashSet

Generics and Javas Collection Classes 21 ge·ner·ic adjective \jə ̇ˈ nerik, -rēk\ relating or applied to or descriptive of all members of a genus, species, class, or group: common to or characteristic of a whole group or class: typifying or subsuming: not specific or individual. From Wikipedia: generic programming: a style of computer programming in which algorithms are written in terms of to-be- specified-later types that are then instantiated when needed for specific types provided as parameters. In Java: Without generics, every Vector object contains a list of elements of class Object. Clumsy With generics, we can have a Vector of Strings, a Vector of Integers, a Vector of Genes. Simplifies programming, guards against some errors Read carefully!

Generics: say we want an ArrayList of only one class 22 API specs: ArrayList declared like this: public class ArrayList extends AbstractList implements List … { … } Means: Can create Vector specialized to certain class of objects: vs.add(3); vi.add(abc); These are illegal int n= vs.get(0).size(); vs.get(0) has type String No need to cast ArrayList vs= new ArrayList (); //only Strings ArrayList vi= new ArrayList (); //only Integers

ArrayList to maintain list of Strings is cumbersome 23 ArrayList v= new ArrayList (); … Store a bunch of Strings in v … // Get element 0, store its size in n ArrayList Object Fields that contain a list of objects (o 0, o 1, …, o size()-1 ) Vector() add(Object) get(int) size() remove() set(int, Object) … v ArrayList Only Strings, nothing else String ob= ((String) v.get(0)).length(); int n= ob.size(); All elements of v are of type Object. So, to get the size of element 0, you first have to cast it to String. Make mistake, put an Integer in v? May not catch error for some time.

Generics allow us to say we want Vector of Strings only 24 API specs: Vector declared like this: public class Vector extends AbstractList implements List … { … } Full understanding of generics is not given in this recitation. E.g. We do not show you how to write a generic class. Important point: When you want to use a class that is defined like Vector above, you can write Vector v= new Vector (…); to have v contain a Vector object whose elements HAVE to be of class C, and when retrieving an element from v, its class is C.

Parsing Arithmetic Expressions 25 We show you a real grammar for arithmetic expressions with integer operands; operations +, -, *, /; and parentheses ( ). It gives precedence to multiplicative operations. We write a recursive descent parser for the grammar and have it generate instructions for a stack machine (explained later). You learn about infix, postfix, and prefix expressions. Introduced in lecture briefly, to show use of grammars and recursion. Done more thoroughly and carefully here. Historical note: Gries wrote the first text on compiler writing, in It was the first text written/printed on computer, using a simple formatting application. It was typed on punch cards. You can see the cards in the Stanford museum; visit infolab.stanford.edu/pub/voy/museum/pictures/display/floor5.htm

Parsing Arithmetic Expressions Arithmetic expr in infix notation 5 – 6 + Same expr in postfix notation infix: operation between operands postfix: operation after operands prefix: operation before operands PUSH 5 NEG PUSH 6 ADD Corresponding machine language for a stack machine: PUSH: push value on stack NEG: negate the value on top of stack ADD: Remove top 2 stack elements, push their sum onto stack

Infix requires parentheses. Postfix doesnt 27 (5 + 6) * (4 – 3) Infix * Postfix * 3 Infix * + Postfix Math convention: * has precedence over +. This convention removes need for many parentheses Task: Write a parser for conventional arithmetic expressions whose operands are ints. 1.Need a grammar for expressions, which defines legal arith exps, giving precedence to * / over Write recursive procedures, based on grammar, to parse the expression given in a String. Called a recursive descent parser

Grammar 28 Use 3 syntactic categories:,, A has one of 3 forms: 1. integer 2. – 3. ( ) Show syntax trees for 3 – – 5 – ( ) 3 5– – ) ( – Havent shown grammar yet ::= int | | ( )

Grammar 29 Use 3 syntactic categories:,, A is: followed by 0 or more occurs. of multop where multop is * or / ::= { {* | /}1 } 3 * ( ) * 6 Means: 0 or 1 occurrences of * or / Means: 0 or more occurrences of thing inside { }

Grammar 30 Use 3 syntactic categories:,, A is: followed by 0 or more occurrences of addop where addop is + or ( ) _ 6 ::= { {+ | -}1 }

31 Initialized to a String that contains an arithmetic expression. Delivers the tokens in the String, one at a time Class Scanner Expression: 3445*( ) Tokens: 3445 * ( ) All parsers use a scanner, so they do not have to deal with the input character by character and do not have to deal with whitespace

32 An instance provides tokens from a string, one at a time. A token is either 1. an unsigned integer, 2. a Java identifier 3. an operator + - * / % 4. a paren of some sort: ( ) [ ] { } 5. any seq of non-whitespace chars not included in Class Scanner public Scanner(String s) // An instance with input s public boolean hasToken() // true iff there is a token in input public String token() // first token in input (null if none) public String scanOverToken() // remove first token from input // and return it (null if none) public boolean tokenIsInt() // true iff first token in input is int public boolean tokenIsId() // true iff first token in input is a // Java identifier

33 /** scanner's input should start with a if not, throw a RuntimeException. Return the postfix instructions for and have scanner remove the from its input. ::= an integer | – | ( ) */ public static String parseFactor(Scanner scanner) The spec of every parser method for a grammatical entry is similar. It states 1.What is in the scanner when parsing method is called 2.What the method returns. 3.What was removed from the scanner during parsing. Parser for

34 /** scanner's input should start with an --if not throw a RuntimeException. Return corresponding postfix instructions and have scanner remove the from its input. := { {+ or -}1 } */ public static String parseExp(Scanner scanner) { String code= parseTerm(scanner); while ("+".equals(scanner.token()) || "-".equals(scanner.token())) { String op= scanner.scanOverToken(); String rightOp= parseTerm(scanner); code= code + rightOp + (op.equals("+") ? "PLUS\n" : "MINUS\n"); } return code; } Parser for