Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.

Slides:



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

CS 206 Introduction to Computer Science II 09 / 05 / 2008 Instructor: Michael Eckmann.
Exercise 1 Suppose C is a class that implements interfaces I and J. Which of the following Requires a type cast? C c = ……? I i = …..? J j = …..? c =
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Computer Science 209 Software Development Iterators.
Comparable and Comparator Nuts and Bolts. 2 Nuts and bolts Four methods underlie many of Java’s important Collection types: equals, compare and compareTo,
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
12-Jul-15 Lists in Java Part of the Collections Framework.
More sophisticated behavior Using library classes to implement some more advanced functionality 3.0.
Programming with Collections Grouping & Looping - Collections and Iteration Week 7.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 22 Lists, Stacks, Queues, and Priority.
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
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.
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Grouping objects Collections and iterators. Main concepts to be covered Collections Loops Iterators.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Composition (Part 2) 1. Class Invariants  class invariant  some property of the state of the object that is established by a constructor and maintained.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
A Singleton Puzzle: What is Printed? 1 public class Elvis { public static final Elvis INSTANCE = new Elvis(); private final int beltSize; private static.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
10-Nov-15 Java Object Oriented Programming What is it?
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
JAVA COLLECTIONS M. TAIMOOR KHAN (ADAPTED FROM SWINBURNE NOTES)
Goals for Today 1  Multiton  maps  static factory methods.
Mixing Static and Non-static
Inheritance (Part 4) Polymorphism and Abstract Classes 1.
CS1101: Programming Methodology
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
More on Objects Mehdi Einali Advanced Programming in Java 1.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Mixing Static and Non-static Singleton 1. Singleton Pattern 2  “There can be only one.”  Connor MacLeod, Highlander.
Iterator Pattern. Traversing two different collections  When bringing two previously developed objects together, it can be difficult to change an implementation.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Puzzle 2 1  what does the following program print? public class Puzzle02 { public static void main(String[] args) { final long MICROS_PER_DAY = 24 * 60.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
Important Annoucement 1  I messed up something in the last class  if a subclass overrides a method that throws an exception then it must either 1. throw.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
1 clone() Defined in Object Creates an identical copy –Copies pointers to fields (does not copy fields of fields) –Makes a shallow copy if the object’s.
Iterators. Iterator  An iterator is any object that allows one to step through each element in a list (or, more generally, some collection).
1 Iterators & the Collection Classes. 2 » The Collection Framework classes provided in the JAVA API(Application Programmer Interface) contains many type.
Iterators.
Objects First with Java CITS1001 week 4
Software Development Iterators
Java Software Structures: John Lewis & Joseph Chase
Comparable and Comparator
Comparable and Comparator
Creating and Modifying Text part 3
Objects with ArrayLists as Attributes
Presentation transcript:

Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1

Implementing a Deck of Cards  a class to represent a deck of cards  a deck has-a collection of 52 cards  the deck should own the cards  a deck is a composition of cards  a client can ask the deck to deal a card  the deck gives up ownership of the card  the client takes ownership of the card  a client can try to give a dealt card back to the deck  the deck takes ownership of the card if and only if it does not have the same card already  class invariant: the cards in a deck are unique 2

 a client can ask for the deck to be shuffled  a client can ask to see all of the cards without the deck giving up ownership of any of the cards  we will implement the Iterable interface for the deck  lets clients write code like: Deck theDeck = new Deck(); for(Card c : theDeck) // for each Card c in theDeck { System.out.println(c); } 3 Deck List 1 filled diamond indicates composition

Iterators  an iterator is an object that provides access to each element of a collection in sequential order  an iterator must implement the Iterator interface found in java.util public interface Iterator { public boolean hasNext(); public E next(); public void remove(); // optional } 4 [AJ 16.3]

Iterable Interface  every Collection type supplies an iterator by implementing the Iterable interface public interface Iterable { public Iterator iterator(); } 5

Iterating with hasNext  prior to Java 1.5 you would iterate over a Collection like so 6 import java.util.ArrayList; import java.util.Iterator; //... ArrayList lst = new ArrayList (); lst.add("apple"); lst.add("banana"); lst.add("mango"); for(Iterator iter = lst.iterator(); iter.hasNext(); ) { String s = iter.next(); System.out.println(s.replace('a', 'A') + " "); } // prints Apple bAnAnA mAngo

Iterating with for-each  the preferred method is to use a for-each loop 7 import java.util.ArrayList; import java.util.Iterator; //... ArrayList lst = new ArrayList (); lst.add("apple"); lst.add("banana"); lst.add("mango"); for(String s : lst) // for each String s in lst { System.out.println(s.replace('a', 'A') + " "); } // prints Apple bAnAnA mAngo

Deck package playingcard; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ArrayList; public class Deck implements Iterable { private final List cards; 8

Deck public Deck() { this.cards = new ArrayList (); this.reset(); } public void reset() { this.cards.clear(); final Set keys = CardUtil.RANKS.keySet(); for(String rank : keys) { for(String suit : CardUtil.SUITS) { cards.add(new Card(rank, suit)); } 9 The Deck owns its Cards; thus it must create and own its own List of Cards. Map does not supply an iterator to its keys or values, but it can return its keys as a Set.

Deck public void shuffle() { Collections.shuffle(this.cards); } public int getNumberOfCards() { return this.cards.size(); } 10

Deck public Card deal() { Card c = null; if(this.getNumberOfCards() > 0) { c = this.cards.remove(0); } return c; } 11 When a Deck deals a Card, it is giving up ownership of the Card; therefore, the Deck needs to remove the Card from its internal state. In this case, we always deal from the top of the Deck, so we remove the first Card stored in the List this.cards (the zero th card).

Deck public boolean take(Card c) { boolean ok = false; if (!this.cards.contains(c)) { ok = this.cards.add(c); } return ok; } 12 A client can ask a Deck to take a Card from the client; in this case, the client is asking the Deck to take ownership of the Card. Because of the class invariant (Deck holds unique Cards), the take implementation must check that the Card c is not already in this.cards. The Deck takes ownership of the Card c if and only if it does not already have a card identical to c.

Implementing equals for Deck  you might be tempted to write something like the following in equals() eq = this.cards.equals(other.cards);  unfortunately, this does not work because the order of the list elements matters for List.equals()  a list with elements { 1, 2, 3, 4 } is not equals to a list with elements { 4, 3, 2, 1 } 13

 we can use List.containsAll()  a list with elements { 1, 2, 3, 4 } contains all of the elements in the list { 4, 3, 2, 1 }  but a list with elements { 1, 2, 3, 4 } also contains all of the elements in the list { 4, 3 }  we will say that two Decks are equal if they have the same number of cards and they contain the same cards 14

Deck public boolean equals(Object obj) { boolean eq = false; if (this == obj) { eq = true; } else if( obj != null && this.getClass() == obj.getClass() ) { Deck other = (Deck) obj; eq = this.cards.size() == other.cards.size() && this.cards.containsAll(other.cards); } return eq; } 15

Deck public Iterator iterator() { return this.cards.iterator(); } 16 Because Deck implements Iterable, we must provide a method that returns an iterator to a Card. We could implement our own Card iterator class, but the List contained by the Deck already supplies an iterator for us. In this case, we can just delegate to this.cards to get a suitable iterator.

Exercises  add a constructor that constructs a Deck given a Collection of Cards public Deck(Collection cards)  hint: use the Collections utility  add a method that sorts the Deck by rank public void sort()  hint: use the Collections utility  implement toString() 17

PEx02 Default constructor /** * Constructs a person of age 0 whose name is either * John Doe or Jane Doe. The name is randomly chosen. */ public Person() { Random gen = new Random(); if (gen.nextBoolean()) { this.name = "John Doe"; } else { this.name = "Jane Doe"; } this.age = 0; } 18

PEx02 Two-parameter Constructor /** * Constructs a person with the given name and age. * name The name of the person. age >= 0 age The age of the person. */ public Person(String name, int age) { if (age < 0) { throw new IllegalArgumentException("age must be greater than or equal to zero"); } this.name = name; this.age = age; } 19 Remember that as the implementer, you can do whatever you want if the precondition is violated: age = 0; instead of the exception would also be acceptable.

PEx02 equals /** * Tests for equality of this person and the given * other person. Two persons are equal if they have * the same name and the same age. If both names are * null, then they are considered the same. * Another person. true if this person and the other person are * the same, false otherwise. public boolean equals(Object object) { 20

boolean eq = false; if (this == object) { eq = true; } else if (object != null && this.getClass() == object.getClass()) { // 1. cast object to Person then // 2. do attribute by attribute equals keeping in mind // that some attributes might need special // handling because they can be null 21

Person other = (Person) object; if (this.age == other.age) { if (this.name == null && other.name == null) { eq = true; } else if (this.name.equals(other.name)) { eq = true; } return eq; } 22

Puzzle 05 What does the following print? import java.util.*; public class DatingGame { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); cal.set(1999, 12, 31); // Dec 31, 1999? System.out.println(cal.get(Calendar.YEAR) + " "); Date d = cal.getTime(); System.out.println(d.getDay()); } 23 from Java Puzzlers by Joshua Bloch and Neal Gafter