Presentation is loading. Please wait.

Presentation is loading. Please wait.

Abstract Data Types Chapter 1.

Similar presentations


Presentation on theme: "Abstract Data Types Chapter 1."— Presentation transcript:

1 Abstract Data Types Chapter 1

2 Today Data Types & Abstract Data Types Designing Systems and ADTs
use cases class-responsibility-collaboration cards (CRC) unified modeling language (UML) An Example ADT: the Bag

3 Data Structures Structure  arrangement
data structure  arrangement of data Some come with programming language data types Others developed by programmers some standardized—various Java packages others built to order

4 Data Types Computer languages offer data types
int, float, char, array of type, record of types, … Each type comes with some operations defined for it addition, multiplication, equality check, select an element, select a field, … Different languages/dialects may offer slightly different options

5 Abstract Data Types “Abstract” means not associated with any particular language/dialect/machine data types as they are in mathematics Data types implement ADTs int implements integer, float implements real usually restricted somehow Ideal is to make close to the model ADT

6 Abstraction Focus on what instead of how
car’s controls: gas, brakes, steering wheel, … what: accelerate, decelerate, turn, … how: gas? diesel? electric? drum? disk? gears? wire? for the driver, how doesn’t really matter driving an electric car much like driving any other design for the driver!

7 ADT Parts Domain of the ADT Operations Note: what values are there
functions defined over those values may involve other types Note: no decision on how to represent the values no decision on how to implement the operations

8 ADTs and Interfaces Interface specifies what can be done
Does not specify how it will be done Interface has no data fields BUT it’s designed with the data in mind operations are defined on the data operations take/modify/return data Java interfaces are data types

9 System Design Actors: who or what will use the system?
Scenarios: what will they be doing? University registration system actors: student & registrar scenarios: apply (student) enroll (registrar) add course (either) drop course (either)

10 Develop a Scenario “Use Case”: describe actor in scenario
Identify the nouns  look for classes/data Identify the verbs  look for methods Student adding a course: Student enters ID information System confirms student is registered Student selects course and section from list(s) If there is no time conflict: add course to student’s schedule

11 Develop a CRC Responsibilities Collaborations Student’s Schedule
Which scenarios? Methods in scenarios? Collaborations Which other classes are involved? Student’s Schedule add a section, remove a section, check for time conflict, … student has one schedule, but multiple sections

12 UML Diagrams Semi-formal way to represent information
class/interface name data methods + means public name: type Schedule (one or more sections) +addSection(s: Section) +removeSection(s: Section) +isTimeConflict(s: Section): boolean +show()

13 UML Diagrams Semi-formal way to represent information
lines/arrows for collaborations numbers on ends: how many of this for each each schedule has 0 to 10 sections (*  any #) arrows: schedule has sections; section no schedules Student Schedule Section Course 1 1 0..10 1 * *

14 <<interface>>
UML Diagrams Semi-formal way to represent information open-head arrows for inheritance interfaces labeled <<interface>> Student <<interface>> Measurable GradStudent UndergradStudent

15 Sample ADT: the Bag A finite collection of objects in no particular order, possibly with duplicates compare a list: in some particular order compare a set: no duplicates allowed Lists, sets and bags are all containers object to group other objects similar actions

16 Use Cases Assume we already went thru this process and discovered that we need a bag a bag is a fairly useful thing Only collaboration is the kind of things we want to put into the bag Only responsibilities are the methods for working with the bag

17 Bag CRC Responsibilities:
get # of items currently in bag see whether bag is empty add given object to bag remove given object from bag remove some unspecified object from bag empty the bag check whether some object is in the bag count duplicates of some object in the bag list all objects in the bag Collaboration: class of objects bag can contain

18 Things Can Go Wrong! Asked to remove item that’s not there
Asked for list element with negative index Need to decide what to do BAD things to do: ignore command don’t remove anything, don’t warn client try to “fix” the request take absolute value of index and return that item

19 Dealing with Unusual Conditions
Make client responsible to avoid it document the “precondition” on the operation Return a boolean value true  that worked; false  that didn’t Return a special value for failed operations not a valid return value! (null might work) Throw an exception

20 Bag Operation Failures
When adding an item, bag may be full return true if item was added, false otherwise When removing a specific item, not there return true if item was removed, false otherwise When removing “some” item, empty bag return null (NOTE: can’t keep nulls in the Bag) Incorporate these decisions into the design

21 Bag UML Diagram T is a “generic” type
each bag will specify its own “base” type Bag +getCurrentSize(): integer +isEmpty(): boolean +add(newEntry: T): boolean +remove(anEntry: T) : boolean +remove(): T +clear(): void +contains(anEnty: T): boolean +getFrequencyOf(enEntry: T): integer +toArray(): T[] T * *

22 Generic Types in Java You’ve seen these
ArrayList<Integer>, List<String>, … Use a generic name in the declaration usually one capital letter public class ArrayList<B> // B for “Base” public interface List<E> // E for “Element” public class Bag<T> // T for “Type” use that name in the method declarations public boolean add(T newEntry) { … }

23 Revised Bag UML Diagram
T is a “generic” type each bag will specify its own “base” type Bag<T> +getCurrentSize(): integer +isEmpty(): boolean +add(newEntry: T): boolean +remove(anEntry: T) : boolean +remove(): T +clear(): void +contains(anEnty: T): boolean +getFrequencyOf(enEntry: T): integer +toArray(): T[]

24 Bag Implementation/Interface
Want to allow multiple ways to implement an array, a linked list, a kind of structure that hasn’t even been invented yet! Each implementation is its own class ArrayBag, LinkedBag, QuantumBag, … For the ADT, we create an interface BagInterface

25 BagInterface public interface BagInterface<T> { public int getCurrentSize (); public boolean isEmpty (); public boolean add (T newEntry); public boolean remove (T anEntry); public T remove (); public void clear (); public boolean contains (T anEntry); public int getFrequency (T anEntry); public T[] toArray (); }

26 Document the Interface
Add javadoc comments to the interface Add javadoc comments to all methods (See the text/on-line code)

27 Using the ADT Bag We can use the ADT in our programs
On-line shopper program from text bag to put purchased items in base class Item (name and price) Overview of program add several items to bag remove items one at a time, adding to cost, until bag is empty

28 coins: BagInterface<Coin>
Using the ADT Bag Can use the ADT in other classes PiggyBank class from text instance variable: a Bag of Coins base class Coin (value and year minted) PiggyBank UML shake to see if empty drop a coin in shake till coin falls out PiggyBank coins: BagInterface<Coin> +isEmpty(): boolean +add(newEntry: Coin): boolean +remove(): Coin

29 Our First Bag Implementation
HumanBag a class that asks the user to hold the bag user adds/removes items, answers questions Only implements BagInterface<String> HumanBag not a generic type

30 More Review Material Review of interfaces Comparable Comparator

31 Interface Summary An interface is a data type
variables can have that data type including (especially) parameters for methods such variables (methods) called polymorphic An interface lists public methods each implementing class implements them each class has its own implementation these classes are similar kinds of things Circles and Rectangles are similar kinds of things

32 The Comparable<…> Interface
Collections.sort sorts Lists of some types Java must know how to sort them knows how to sort Integer, Double, String, … doesn’t know how to sort user-defined classes Tell Java how to sort user-defined classes implement the Comparable<…> interface Collections.sort expects to be given a List<Comparable<…>>

33 The Comparable<…> Interface
Have to fill in the <…> what kind of thing it can be sorted with almost always itself public class Student implements Comparable<Student> Has exactly one method compareTo says how to compare to other public int compareTo(Student other) how does this Student compare to other Student for Professor: public int compareTo(Professor other)

34 Sorting Students Let’s sort Students by name name is a String
String has a compareTo method so just return whatever it returns public int compareTo(Student other) { return this.name.compareTo(other.name); } “if you want to compare Students, compare their names.” See byName/Student.java

35 Sorting Students Add Students to list; sort list; print list
List<Student> ss = new ArrayList<>(); ss.add(new Student(“Jake”)); ss.add(new Student(“Angie”)); ss.add(new Student(“Geety”)); Collections.sort(ss); System.out.println(ss); [Angie (A ), Geety (A ), Jake (A )] See byName/SortStudents.java

36 Sorting by Grade Sorting by numbers uses subtraction
smallest to largest: this.number – other.number largest to smallest: other.number – this.number but result must be an int! public int compareTo(Student other) { return other.getAverage() – this.getAverage(); } sorts Students from highest to lowest grade See byGrade/Student.java and byGrade/SortStudents.java

37 Sorting by Double Values
Need to change double to int (int) no good – changes 0.5 to 0 instead of 1 Use Math.signum to get sign of result then change to int public int compareTo(Line other) { double result = this.length – other.length; double sign = Math.signum(result); // -1.0, 0.0, or +1.0 return (int)sign; } sorts from shortest to longest See Line.java and SortLines.java

38 Exercise Write a compareTo method that sorts Students by A_NUMBER
remember, it’s a String Write a compareTo method that sorts Lines from longest to shortest each Line has a length

39 Sorting in Many Ways Sometimes want to sort by name, other times by grade (and other times by A#) Collections.sort accepts a second argument it’s a “way to sort” Collections.sort(words, String.CASE_INSENSITIVE_ORDER); we’ll want (at least) these “ways to sort”: Student.BY_NAME Student.BY_GRADE Student.BY_ANUMBER

40 The Comparator<…> Interface
The interface for “ways to sort” Need a class to implement the interface so we need three classes public class SortStudentsByName implements Comparator<Student> { … } public class SortStudentsByGrade implements Comparator<Student> { … } public class SortStudentsByANumber implements Comparator<Student> { … } See the folder comparators/withClasses in this week’s sample code

41 The Comparator<…> Interface
The interface for “ways to sort” has exactly one method: int compare(_, _) very similar to compareTo method public class SortStudentsByName implements Comparator<Student> { public int compare(Student one, Student other) { return one.getName().compareTo(other.getName()); }

42 Student Comparators Each comparator in Student is a Comparator
each one is an object of the corresponding class public static final Comparator<Student> BY_NAME = new SortStudentsByName(); public static final Comparator<Student> BY_GRADE = new SortStudentsByGrade(); public static final Comparator<Student> BY_ANUMBER = new SortStudentsByANumber(); See comparators/withClasses/Student.java

43 All Those Extra Classes?
Don’t actually need to create new files don’t need SortStudentsByName.java &c. Use “anonymous” classes instead put Comparator definition inside Student.java public static final Comparator<Student> BY_NAME = new Comparator<Student>() { public int compare(Student one, Student other) { return one.getName().compareTo(other.getName()); } }; See the folder comparators/anonymous in this week’s sample code

44 Anonymous Classes Class without a name
can use it to implement any interface just need to give the definitions SomeInterface blah = new SomeInterface() { // define all interface methods in here! }; only makes sense for some interfaces nothing that needs its own instance variables Comparator makes sense; Comparable doesn’t

45 Questions


Download ppt "Abstract Data Types Chapter 1."

Similar presentations


Ads by Google