5-1 Data types: values, operations, and data representation. Abstract data type: values and operations only. Requirements, contract, implementation(s).

Slides:



Advertisements
Similar presentations
Linear Lists – Array Representation
Advertisements

Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Air Force Institute of Technology Electrical and Computer Engineering
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Chapter 3 DATA: TYPES, CLASSES, AND OBJECTS. Chapter 3 Data Abstraction Abstract data types allow you to work with data without concern for how the data.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
Hash Tables1 Part E Hash Tables  
Fundamental Programming Structures in Java: Strings.
1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Odds and Ends Strings (from Chapter 9) StringTokenizer.
1 CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Classes in C++ Bryce Boe 2012/08/15 CS32, Summer 2012 B.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Abstract Data Types (ADTs) and data structures: terminology and definitions A type is a collection of values. For example, the boolean type consists of.
Course: Object Oriented Programming - Abstract Data Types Unit1: IntroductionSlide Number 1 Introduction Course: Object Oriented Programming Abstract Data.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
6 Stack ADTs  Stack concepts  Stack applications  Stack ADTs: requirements, contracts  Implementations of stacks: using arrays and linked-lists  Stacks.
Data Structures Chapter 1- Introduction Mohamed Mustaq.A.
2-1 Week 2 Sets Set concepts (you should know these!) Set applications. A set ADT (abstract data type): requirements, contract. Implementations of sets:
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.
Lec 6 Data types. Variable: Its data object that is defined and named by the programmer explicitly in a program. Data Types: It’s a class of Dos together.
The java.lang Package chapter 8 Java Certification Study Group February 2, 1998 Seth Ladd.
Data Structures and Algorithms -- Chapter 3 Abstract Data Types Mohamed Mustaq.
Hash Tables1   © 2010 Goodrich, Tamassia.
Introduction to Java Java Translation Program Structure
Defining Classes II. Today’s topics  Static methods  Static variables  Wrapper classes  References  Class parameters  Copy constructor.
© 2004 Goodrich, Tamassia Hash Tables1  
Chapter 7: Characters, Strings, and the StringBuilder.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
6 Strings and Tuples © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
1 Introduction  Algorithms  Data structures  Abstract data types  Programming with lists and sets © 2008 David A Watt, University of Glasgow Algorithms.
9-1 9 Set ADTs Set concepts. Set applications. A set ADT: requirements, contract. Implementations of sets: using arrays, linked lists, boolean arrays.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
9 Set ADTs  Set concepts  Set applications  A set ADT: requirements, contract  Implementations of sets: using member arrays, linked lists, boolean.
Chapter 8 Searching and Sorting © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
Introduction to Objects and Encapsulation Computer Science 4 Mr. Gerb Reference: Objective: Understand Encapsulation and abstract data types.
Individual Testing, Big-O, C++ Bryce Boe 2013/07/16 CS24, Summer 2013 C.
Attribute - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/24/2016.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
String & Exception. Lesson plan Class & Object String Exercise for midterm.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
Basic Data Types อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 4.
The Methods and What You Need to Know for the AP Exam
11 Map ADTs Map concepts. Map applications.
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Primitive Types Vs. Reference Types, Strings, Enumerations
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
The Building Blocks Classes: Java class library, over 1,800 classes:
Java Classes and Objects 3rd Lecture
8 List ADTs List concepts. List applications.
Classes and Objects Systems Programming.
Presentation transcript:

5-1 Data types: values, operations, and data representation. Abstract data type: values and operations only. Requirements, contract, implementation(s). (Design of abstract data types.) String abstract data types. Abstract data types in the Java class library. 5 Abstract Data Types © 2001, D.A. Watt and D.F. Brown

5-2 Data types We classify all data into data types, such as:  Booleans  integers  objects of various classes. Each data type is characterized by:  a set of values  a data representation (which is common to all these values)  a set of operations (which can be applied uniformly to all these values).

5-3 Java data types TypeValuesData representation Operations boolean false, true1 byte || && ! char Unicode characters2 bytes (as for int ) int negative, zero, positive whole numbers 32-bit twos- complement + - * / % == etc. float negative, zero, positive floating-point numbers IEEE 32-bit floating-point String sequences of charactersarray of characters + length charAt etc.

5-4 Introducing new data type To introduce a new data type, we must define its values, data representation, and operations. In Java, use a class declaration:  The class’s instance variables determine the values and data representation.  The class’s constructors and methods are the operations. Each object of the class:  has those instance variables  is created by one of those constructors  may be inspected and/or updated by any of those methods.

5-5 Example 1 (2) Possible application code: Person p1 = new Person("Curie", "Pierre", 1859); Person p2 = new Person("Sklodowska", "Marie", 1867); … p2.changeName(p1.surname);

5-6 Example 2: Date data type (1) Class declaration: public class Date { // Each Date value is a past, present, or future date. // This date is represented by a year number y, a month number // m (1…12), and a day-in-month number d (1…31): public int y, m, d; public Date (int y, int m, int d) { // Construct a date with year y, month m, and day-in-month d. if (m < 1 || … ) throw … ; this.y = y; this.m = m; this.d = d; }

5-7 Example 2 (2) Class declaration (continued): public void advance (int n) { // Advance this date by n days (where n ≥ 0). int y = this.y, m = this.m, d = this.d + n; for (;;) { int last = …; // no. of days in m, y if (d <= last) break; d -= last; if (m < 12) m++; else { m = 1; y++; } } this.y = y; this.m = m; this.d = d; } }

5-8 Example 2 (3) Possible application code: Date today = new Date(2001, 2, 14); today.advance(16); System.out.println(today.y + '-' + today.m + '-' + today.d); This should print “ ”.

5-9 Example 2 (4) Problem: This data representation admits improper values (e.g., m = 0; or m = 2 and d = 30). Constructors and methods can (should) be coded to avoid improper values. E.g.: Date today = new Date(2001, 2, 30); will throw an exception. But what if the data representation is accessed directly? Date today = new Date(2001, 2, 14); today.d += 16;

5-10 Example 3: Date data type again (1) A different data representation is possible: public class Date { // Each Date value is a past, present, or future date. // This date is represented by a day-in-epoch number d // (where 0 represents 1 January 2000): public int d; public Date (int y, int m, int d) { … } public void advance (int n) { … } } This makes advance faster, but Date() slower.

5-11 Example 3 (2) Recall existing application code: Date today = new Date(2001, 2, 14); today.advance(16); System.out.println(today.y + '-' + today.m + '-' + today.d); fails to compile yields wrong value fails to compile

5-12 Public vs. private data representation If the data representation is public: –Application code might make improper values. –Existing application code might be invalidated by change of representation. If the data representation is private: +Application code cannot make improper values. +Existing application code cannot be invalidated by change of representation.

5-13 Abstract data types An abstract data type (ADT) is characterized by:  a set of values  a set of operations. It is not characterized by its data representation. The data representation is private, so application code cannot access it. (Only the operations can.) The data representation is changeable, with no effect on application code. (Only the operations must be recoded.)

5-14 ADT specification (1) Each ADT should have a contract that:  specifies the set of values of the ADT  specifies each operation of the ADT (i.e., the operation’s name, parameter type(s), result type, and observable behavior). The contract does not specify the data representation, nor the algorithms used to implement the operations. The observable behavior of an operation is its effect as ‘observed’ by the application code.  Example of observable behavior: search an array.  Examples of algorithms with that behavior: linear search, binary search.

5-15 ADT specification (2) The ADT programmer undertakes to provide an implementation of the ADT that respects the contract. The application programmer undertakes to process values of the ADT using only the operations specified in the contract. Separation of concerns:  The ADT programmer is not concerned with what applications the ADT is used for.  The application programmer is not concerned with how the ADT is implemented. Separation of concerns is essential for designing and implementing large systems.

5-16 Example 4: contract for Date ADT (1) Assumed application requirements: 1)*** The values must be all past, present, and future dates. 2)*** It must be possible to construct a date from year number y, month number m, and day-in-month number d. 3)It must be possible to compare dates. 4)It must be possible to render a date in ISO format “y-m-d”. 5)It must be possible to advance a date by n days.

5-17 En Java - généralité Spécifier un contrat comme une interface  Méthodes exigées Déclarer une clase conforme à cette interface  Choix des structures de données et définition des attributs  Implantation de toutes les méthodes exigées Utilisation de la classe dans une application

5-18 Spécifier un contrat en Java Interface:  Constante  Méthode abstraite Mécanisme idéal en Java pour définir un ADT (Un autre mécanisme possible est la classe abstraite) Note: les spécifications présentées ici sont modifiées par rapport au livre (class -> interface)

5-19 Example 4 (2) Possible contract, expressed as an interface: public interface DateADT { // Each Date value is a past, present, or future date. public int compareTo (Date that); // Return –1 if this date is earlier than that, // or 0 if this date is equal to that, // or +1 if this date is later than that. public String toString (); // Return this date rendered in ISO format. public void advance (int n); // Advance this date by n days (where n ≥ 0). }

5-20 Définir une classe conforme à une interface Utiliser ‘implements’ Exemple class implements { }

5-21 Exemple 4 class Date implements DateADT { private …// les attributs de la classe public Date(int y, int m, int d) {... } //constructeur public int compareTo (Date that) {... } public String toString () {...} public void advance (int n) {...}... }

5-22 Example 4 (4) Possible application code: Date today = … ; Date easter = new Date(2001, 4, 15); today.advance(16); if (today.compareTo(easter) < 0) System.out.println(today.toString()); Impossible application code: today.d += 16; System.out.println(today.y + '-' + today.m + '-' + today.d); fails to compile

5-23 ADT implementation (in a class) An implementation of an ADT entails:  choosing a data representation  choosing an algorithm for each operation. The data representation must be private. The data representation must cover all possible values. The algorithms must be consistent with the data representation.

5-24 Example 5: first implementation of Date ADT (1) Class declaration: public class Date implements DateADT { // Each Date value is a past, present, or future date. // This date is represented by a year number y, a month number // m, and a day-in-month number d : private int y, m, d; public Date (int y, int m, int d) { // Construct a date with year y, month m, and day-in-month d. this.y = y; this.m = m; this.d = d; }

5-25 Example 5 (2) Class declaration (continued) – implementation of the required methods: public int compareTo (Date that) { // Return –1 if this date is earlier than that, // or 0 if this date is equal to that, // or +1 if this date is later than that. return (this.y that.y ? +1 : this.m that.m ? +1 : this.d that.d ? +1 : 0); }

5-26 Example 5 (3) Class declaration (continued): public String toString () { // Return this date rendered in ISO format. return (this.y + '-' + this.m + '-' + this.d); } public void advance (int n) { // Advance this date by n days (where n ≥ 0). … } } complicated

5-27 Example 6: second implementation of Date ADT (1) Class declaration: public class Date implements DateADT{ // Each Date value is a past, present, or future date. // This date is represented by a day-in-epoch number d // (where 0 represents 1 January 2000): private int d; public Date (int y, int m, int d) { // Construct a date with year y, month m, and day-in-month d. … ; this.d = … ; } complicated

5-28 Example 6 (2) Class declaration (continued): public int compareTo (Date that) { // Return –1 if this date is earlier than that, // or 0 if this date is equal to that, // or +1 if this date is later than that. return (this.d that.d ? +1 : 0); }

5-29 Example 6 (3) Class declaration (continued): public String toString () { // Return this date rendered in ISO format. int y, m, d; … ; return (y + '-' + m + '-' + d); } public void advance (int n) { // Advance this date by n days (where n ≥ 0). this.d += n; } } complicated

5-30 ADT design (1) A constructor is an operation that creates a value of the ADT (dans une classe qui implante cet ADT) An accessor is an operation that uses a value of the ADT to compute a value of some other type. A transformer is an operation that computes a new value of the same ADT. A well-designed ADT provides at least one constructor, at least one accessor, and at least one transformer. The constructors and transformers together can generate all values of the ADT.

5-31 ADT design II (2) A transformer is:  mutative if it overwrites the old value with the new value  applicative if it returns the new value, without overwriting the old value. The values of an ADT are:  mutable if the ADT provides at least one mutative transformer  immutable if the ADT provides no mutative transformer. Ces caractéristiques déterminent le choix d’une structure de données.

5-32 Example 8: design of Date ADT (1) Recall the Date contract of Example 4: public interface DateADT { // private … ; // public Date (int y, int m, int d); public int compareTo (Date that); public String toString (); public void advance (int n); } constructor mutative transformer accessor

5-33 Example 8 (2) Consider another possible Date contract: public inerface DateADT2 { // private … ; // public Date (int y, int m, int d); public int compareTo (Date that); public String toString (); public Date plus (int n); } constructor applicative transformer accessor

5-34 Strings A string is a sequence of characters. The characters have consecutive indices. A substring of a string is a subsequence of its characters. The length of a (sub)string is its number of characters. The empty string has length zero.

5-35 String ADTs Assumed application requirements: 1)The values are to be strings of any length. 2)It must be possible to determine the length of a string. 3)It must be possible to obtain the character at a given index. 4)It must be possible to obtain the substring at a given range of indices. 5)It must be possible to compare strings lexicographically. 6)It must be possible to concatenate strings.

5-36 Immutable strings: contract (1) Possible contract expressed as an outline class declaration: public interface StringADT { // Each String value is an immutable string of characters, // of any length, with indices starting at 0. // private … ; /////////////// Constructor /////////////// // public String (char[] cs); // Construct a string consisting of all the chars in cs.

5-37 Immutable strings: contract (2) Possible contract (continued): /////////////// Accessors /////////////// public int length (); // Return the length of this string. public char charAt (int i); // Return the character at index i in this string. public bool equals (String that); // Return true if and only if this string is equal to that. public int compareTo (String that); // Return –1 if this string is lexicographically less than that, // or 0 if this string is equal to that, // or +1 if this string is lexicographically greater than that.

5-38 Immutable strings: contract (3) Possible contract (continued): /////////////// Transformers /////////////// public String substring (int i, int j); // Return the substring of this string consisting of the characters // whose indices are i, …, j –1. public String concat (String that); // Return the string obtained by concatenating this string and // that. } applicative transformers

5-39 Immutable strings: implementations Represent a string by its length n together with an array of exactly n characters, e.g.: Or represent a string by its length n together with an SLL of characters, e.g.: The array representation is much better. Since these strings are immutable, we never insert or delete characters. 4‘J’‘a’‘v’‘a’ 3210length ‘J’‘a’‘v’‘a’4 length first

5-40 Mutable strings: contract (1) Possible contract expressed as an intertface declaration: public interface MutableStringADT { // Each MutableString value is a mutable string, of any // length, with indices starting at 0. // private … ; /////////////// Constructor /////////////// // public MutableString (); // Construct an empty mutable string.

5-41 Mutable strings: contract (2) Possible contract (continued): /////////////// Accessors /////////////// public int length (); // Return the length of this string. public char charAt (int i); // Return the character at index i in this string. public int compareTo (MutableString that); // Return –1 if this string is lexicographically less than that, // or 0 if this string is equal to that, // or +1 if this string is lexicographically greater than that. public String substring (int i, int j); // Return the substring of this string consisting of the characters // whose indices are i, …, j –1.

5-42 Mutable strings: contract (3) Possible contract (continued): /////////////// Transformers /////////////// public void setCharAt (int i, char c); // Set the character at index i in this string to c. public void append (String s); // Insert the characters of s after the last character of this string. public void insert (int i, String s); // Insert the characters of s before the character at index i in // this string. public void delete (int i, int j); // Delete the characters of this string whose indices are i, …, // j –1. } Question: Tableau ou liste? mutative transformers

5-43 ADTs in the Java class library Class java.lang.String is similar to String above. Class java.lang.StringBuffer is similar to MutableString above. Interface java.util.List supports lists. Interface java.util.Set supports sets. Interface java.util.Map supports maps (tables). Packages java.awt, java.io, java.util, etc., support many other ADTs.