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,

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

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.
Stacks & Their Applications COP Stacks  A stack is a data structure that stores information arranged like a stack.  We have seen stacks before.
Stacks - 3 Nour El-Kadri CSI Evaluating arithmetic expressions Stack-based algorithms are used for syntactical analysis (parsing). For example.
Stacks Chapter 5. Chapter Objectives  To learn about the stack data type and how to use its four methods: push, pop, peek, and empty  To understand.
Stacks Chapter 5. Chapter 5: Stacks2 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop, peek, and empty.
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,
Java Collections. Lecture Objectives To understand the concepts of Java collections To be able to implement Java programs based on Collections.
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,
Stacks. 2 What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
1 Stacks Stack Applications Evaluating Postfix Expressions Introduction to Project 2 Reading: L&C Section 3.2,
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Topic 15 Implementing and Using Stacks
ADTS, GRAMMARS, PARSING, TREE TRAVERSALS Lecture 12 CS2110 – Spring
Chapter 19 Java Data Structures
The Stack and Queue Types Lecture 10 Hartmut Kaiser
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
Exam 1 –Monday June 25 th –open Book / Open Notes –No Electronic Devices (calculators, laptops, etc) –Room Number: W –Time: 5:30pm to 8:00pm.
Topic 3 The Stack ADT.
Comp 245 Data Structures Stacks. What is a Stack? A LIFO (last in, first out) structure Access (storage or retrieval) may only take place at the TOP NO.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
(c) University of Washington14-1 CSC 143 Java Collections.
COMP 121 Week 13: Stacks. Objectives Learn about the stack data type and how to use its four methods: push, pop, peek, and empty Understand how Java implements.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Information and Computer Sciences University of Hawaii, Manoa
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.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Chapter 18 Java Collections Framework
Lecture objectives  Collections interface  Learn about stacks and their methods:  push  pop  peek  Empty  Analyze stack applications and why stacks.
Computer Science 209 Software Development Java Collections.
Data structures Abstract data types Java classes for Data structures and ADTs.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
11/24/ CSC Outline  Stacks  Basic operations  Examples of use  Queues  Basic operations  Examples of use  Implementations  Array-based.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 18: Stacks and Queues (part 2)
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.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
Copyright © Curt Hill Stacks An Useful Abstract Data Type.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
ADTS, GRAMMARS, PARSING, TREE TRAVERSALS Lecture 13 CS2110 – Spring
Click to edit Master text styles Stacks Data Structure.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Using the Java Collection Libraries COMP 103 # T2
Stacks Stack Abstract Data Type (ADT) Stack ADT Interface
ASTs, Grammars, Parsing, Tree traversals
Stacks Chapter 5.
Chapter 19 Java Data Structures
Software Development Java Collections
ASTs, Grammars, Parsing, Tree traversals
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Stacks Chapter 4.
ENERGY 211 / CME 211 Lecture 15 October 22, 2008.
ADTs, Grammars, Parsing, Tree traversals
ASTs, Grammars, Parsing, Tree traversals
CSC 1052 Stacks 1/11/2019.
Collections Framework
Presentation transcript:

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, 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

Generics and Java’s Collection Classes 2 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

Generics with ArrayList and HashSet 3 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!

Generics with ArrayList and HashSet 4 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! Don’t ask what “hash” means. Just know that a Hash Set object maintains a set

Iterating over a HashSet or ArrayList 5 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. Don’t 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.

ArrayList to maintain list of Strings is cumbersome 6 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: say we want Vector of ArrayList only 7 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

Generics allow us to say we want Vector of Strings only 8 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.

9 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 Package java.util has a bunch of classes called e Collection Classes that make it easy to maintain sets of values, list of values, queues, and so on. You should spend dome time looking at their API specifications and getting familiar with them.

10 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

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

Format of ArrayList object 12 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 13 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

Parsing Arithmetic Expressions 14 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 doesn’t 16 (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 17 Use 3 syntactic categories:,, A has one of 3 forms: 1. integer 2. – 3. ( ) Show “syntax trees” for 3 – – 5 – ( ) 3 5– – ) ( – Haven’t shown grammar yet ::= int | | ( )

Grammar 18 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 19 Use 3 syntactic categories:,, A is: followed by 0 or more occurrences of addop where addop is + or ( ) _ 6 ::= { {+ | -}1 }

20 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

21 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

22 /** 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 paring method is called 2.What the method returns. 3.What was removed from the scanner during parsing. Parser for

23 /** 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