6
1 CS121/IS223 Week 11, Slide 1 CS121/IS223 Collections … Revisited Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors CS121/IS223 Week 11, Slide 2 REMINDER There is no class meeting on Thursday April 16 – Please work on the labs! You should aim to get lab 1 and the go shopping question in lab 2 finished this week. Read the project description. If you are going to be working in a pair you have to tell me your pairs on Tuesday 21 April… CS121/IS223 Week 11, Slide 3 Agenda Revisiting arrays – what about arrays of objects? The ArrayList class (compare with arrays) - optional Other useful things… for you to explore: – Iterators – Classes versus interfaces (quick hint on saving objects to files – serializing) – Extras - enumerated types & autoboxing/unboxing CS121/IS223 Week 11, Slide 4 A Recap on Arrays Arrays are objects When an array is passed as a parameter to a method, we use an alias of the original (ORV) – you will learn all about ORVs next week… Arrays can hold primitive types or variables that reference objects (i.e. class types) All elements stored in an array have the same type When we use the new operator to create an array, we give it a type & a size – this is fixed int[] grades = new int[8]; CS121/IS223 Week 11, Slide 5 Array of Cars for the Car Race? Car[] cars = new Car[size]; cars is the variable for accessing the collection of cars Car[] is the type of the cars variable – an array holding Car objects new Car[size] makes an array object that can hold as many Car objects as you state the size to be (it actually holds references to the Car objects) = well, that makes sure that the cars variable is assigned to this array object we just made CS121/IS223 Week 11, Slide 6 Arrays of Objects (i) Dog[] classDogs = new Dog[6]; Actually an array of references to objects Dog[] type classDogs Dog array object (Dog[]) Heap 0 1 2 3 4 5 Examine the code in listings 6.7 – 6.9 (ed 3) or 7.7 – 7.8 (ed 4+) Dog is the base type of the array

cs121 week11 spring09 - SEIDENBERG SCHOOL OF CSIScsis.pace.edu/~ogotel/teaching/cs121_week11_spring09_small.pdf · 5 CS121/IS223 Week 11, Slide 25 To serialize a car object, we invoke

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: cs121 week11 spring09 - SEIDENBERG SCHOOL OF CSIScsis.pace.edu/~ogotel/teaching/cs121_week11_spring09_small.pdf · 5 CS121/IS223 Week 11, Slide 25 To serialize a car object, we invoke

1

CS121/IS223 Week 11, Slide 1

CS121/IS223

Collections … Revisited

Dr Olly Gotel [email protected] http://csis.pace.edu/~ogotel

Having problems? -- Come see me or call me in my office hours -- Use the CSIS programming tutors

CS121/IS223 Week 11, Slide 2

REMINDER

•  There is no class meeting on Thursday April 16 – Please work on the labs!

•  You should aim to get lab 1 and the go shopping question in lab 2 finished this week.

•  Read the project description. If you are going to be working in a pair you have to tell me your pairs on Tuesday 21 April…

CS121/IS223 Week 11, Slide 3

Agenda

•  Revisiting arrays – what about arrays of objects?

•  The ArrayList class (compare with arrays) - optional

•  Other useful things… for you to explore: –  Iterators –  Classes versus interfaces (quick hint on saving

objects to files – serializing) –  Extras - enumerated types & autoboxing/unboxing

CS121/IS223 Week 11, Slide 4

A Recap on Arrays

•  Arrays are objects

•  When an array is passed as a parameter to a method, we use an alias of the original (ORV) – you will learn all about ORVs next week…

•  Arrays can hold primitive types or variables that reference objects (i.e. class types)

•  All elements stored in an array have the same type

•  When we use the new operator to create an array, we give it a type & a size – this is fixed

int[] grades = new int[8];

CS121/IS223 Week 11, Slide 5

Array of Cars for the Car Race?

Car[] cars = new Car[size];

•  cars is the variable for accessing the collection of cars •  Car[] is the type of the cars variable – an array

holding Car objects •  new Car[size] makes an array object that can hold

as many Car objects as you state the size to be (it actually holds references to the Car objects)

•  = well, that makes sure that the cars variable is assigned to this array object we just made CS121/IS223 Week 11, Slide 6

Arrays of Objects (i)

Dog[] classDogs = new Dog[6];

Actually an array of references to objects

Dog[] type

classDogs

Dog array object (Dog[]) Heap

0 1 2 3 4 5

Examine the code in listings 6.7 – 6.9 (ed 3) or 7.7 – 7.8 (ed 4+)

Dog is the base type of the array

Page 2: cs121 week11 spring09 - SEIDENBERG SCHOOL OF CSIScsis.pace.edu/~ogotel/teaching/cs121_week11_spring09_small.pdf · 5 CS121/IS223 Week 11, Slide 25 To serialize a car object, we invoke

2

CS121/IS223 Week 11, Slide 7

Important!

• The array declaration DOES NOT create the array objects … you have to create them separately

CS121/IS223 Week 11, Slide 8

Arrays of Objects (ii)

classDogs[0] = new Dog(); classDogs[1] = new Dog();

Actually an array of references to objects

Dog[] type

classDogs

Dog array object (Dog[]) Heap

0 1 2 3 4 5

Dog object Dog object

CS121/IS223 Week 11, Slide 9

A Worked Example

•  MyDogProgram, Mutts and Dog - See the class code on my website

•  CDs - See the class handout – UML class diagram and code – type this up and play with it

Now do the go shopping question in Lab2 – it is the same pattern!

How about changing the car racing program to have a collection of cars … try seeing if you can do that… practice with all this…

CS121/IS223 Week 11, Slide 10

Reminder!!!

•  ALL the code in the text book is available for you to download and experiment with. DO NOT FORGET THIS… it is useful to do this and to play around with this code!

•  http://duke.csc.villanova.edu/jss1/examples.html

•  Please look at the code in Chapter 7 on this site - download CD.java, CDCollection.java and Tunes.java - run them, try changing them, try adding a method to delete a CD from the collection and to find a CD in the collection based on a title string (Hint - you do this in the CDCollection class). Could you write a program to define students, a collection of students, and a driver class to add new students to a collection, change their grades, check who has the highest grade, etc.? It is the same basic structure and principle as the CD program!

CS121/IS223 Week 11, Slide 11

The ArrayList Class

•  Similar to arrays, but: –  Not fixed in size – they grow & shrink with the

contents (indices adapt) –  Only stores references to objects (not primitives) –  Can store references to multiple types of object –  Can store references to primitives if they are

appropriately wrapped (remember Integer?) –  Can be less efficient than plain old arrays –  Objects forget their type … you have to find this out

when they come out … use obj.getClass()

Must import java.util.ArrayList

Actually implemented using arrays CS121/IS223 Week 11, Slide 12

Major ArrayList Methods

•  boolean add(Object obj) •  void add(int index, Object obj) •  void clear() •  Object remove(int index) •  Object get(int index) •  int indexOf(Object obj) •  boolean contains(Object obj) •  boolean isEmpty() •  int size() Note: The Object class is the root of all classes – so each class type is ultimately also of Object type – we use Object when we want an object but we don’t know what its actual class will be

You can view all available methods in the Java API

Page 3: cs121 week11 spring09 - SEIDENBERG SCHOOL OF CSIScsis.pace.edu/~ogotel/teaching/cs121_week11_spring09_small.pdf · 5 CS121/IS223 Week 11, Slide 25 To serialize a car object, we invoke

3

CS121/IS223 Week 11, Slide 13

Creating & Using an ArrayList

•  Create an ArrayList object: ArrayList dogs = new ArrayList(); //empty

•  Create objects to put into the ArrayList: Dog myDog = new Dog();

•  Call its methods: dogs.add(myDog); //grows a slot to hold a dog

object reference variable

int size = dogs.size(); //returns 1 Dog d = (Dog)dogs.get(0); //remember to cast - I

can do this because I know I am only dealing with dogs! dogs.remove(myDog); //shrinks

CS121/IS223 Week 11, Slide 14

Examples

•  Using an array of objects to do some shopping

•  Using an ArrayList to do some shopping: try the shopping again question in lab2

ArrayList is one of many collections classes in Java (see also Vector, LinkedList, HashSet & others) – a collection is actually an object that represents a group of objects – find out about the Java Collections Framework

-Note I am happy you ignoring ArrayList for now if it is too much as arrays are fine for your project!

Hooks to CS122

CS121/IS223 Week 11, Slide 15

What are Generics?

•  There is a way to avoid the explicit class-casting that you saw with the ArrayList when I had to tell an object it was a Dog -- remember, objects that go into an ArrayList have a memory lapse

•  With <> I can restrict the ArrayList to only hold ONE type of object

ArrayList<Dog> dogs = new ArrayList<Dog>();

•  Java compiler will only allow Dog objects to be added to your collection & will remember what is in the collection when you access

Was new to Java 5.0

CS121/IS223 Week 11, Slide 16

Iterating Over a Collection

•  Common to want to examine every item in a collection

public void getDogs(){ int index = 0; while(index<dogs.size()){ System.out.println(dogs.get(index)); index++; } }

CS121/IS223 Week 11, Slide 17

Iterators

•  An iterator is an object designed to provide functionality to iterate over a collection – luckily it is built-in, just:

import java.util.Iterator; •  ArrayList has a method to give you an Iterator object: Iterator it = yourCollectionName.iterator() •  The Iterator class has 3 methods:

–  hasNext() – are there objects left in collection? Returns boolean

–  next() - returns reference to the next object –  remove() – removes last object returned by next()

•  Call these methods on the it object (i.e. it.next())

Another nifty thing like your Scanner!

CS121/IS223 Week 11, Slide 18

Iterating Over a Collection 2nd Way

•  Make an object do all the hard work for you … this is good OO

public void getDogs(){ Iterator it = dogs.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } Try using this in the lab ArrayList question

My dogs collection (my ArrayList of Dogs) Makes an Iterator object dedicated to iterating/working with your named collection (dogs)

Page 4: cs121 week11 spring09 - SEIDENBERG SCHOOL OF CSIScsis.pace.edu/~ogotel/teaching/cs121_week11_spring09_small.pdf · 5 CS121/IS223 Week 11, Slide 25 To serialize a car object, we invoke

4

CS121/IS223 Week 11, Slide 19

What is Iterator?

•  Iterator is actually an interface that Java Collections classes implement

•  This means that, so long as you provide concrete implementations for the hasNext(), next() & remove() methods, you can make any class you write implement this interface

•  It is up to you to decide what order objects would be returned by next()

•  ArrayList does this all for you…and is ready to go! That makes it nice

CS121/IS223 Week 11, Slide 20

Interfaces

•  An interface lists the public methods available for interacting with an object by declaring abstract methods

•  A class implements an interface if it provides an implementation for each of the abstract methods

•  A class can implement many interfaces

•  We will look in detail at interfaces later in CS606 – they are CRITICAL for good maintainable design

Examine the code in listings 5.9 - 5.11 (3rd ed.) or 6.8-6.10 (4th + ed.)

CS121/IS223 Week 11, Slide 21

Example <<interface>>

public interface Living{ public void breathe(); public void eat(); … }

public class Dog implements Living{ //Provides actual methods for the above –

doggy //specific! E.g.: public void breathe(){ System.out.println(“You all know what this

smells like!”); } … }

Defines an interface & its abstract methods

If a class implements an interface it must provide concrete definitions for all its abstract methods CS121/IS223 Week 11, Slide 22

Another Example

•  Comparable – this is an interface that your objects must implement if they are to be sortable

•  This means that you MUST provide a concrete method body for the compareTo method in the class of the objects you want to compare and sort - it is up to you to decided (for example) how to compare and rank two dogs (size, weight, age?)

CS121/IS223 Week 11, Slide 23

Object Serialization

•  How do you save an object or collection of objects? They have all this state information associated with them!

•  We freeze-dry an object for future reconstitution

•  Enables an object to be stored to a file or transferred elsewhere

•  Object represented as a sequence of bytes

•  We call this, creating a persistent object

•  We make use of: –  the Serializable interface –  the writeObject method of ObjectOutputStream class –  the readObject method of ObjectInputStream class –  (the latter are processing streams)

Advanced placeholder for the project work! If you want to store objects to a file you will need this… canned code

CS121/IS223 Week 11, Slide 24

Say we had a collection of cars to store...

•  If we want to be able to serialize an object, the class of the object and any collection class of the object must implement the Serializable interface

•  This interface has no methods – it is just a hint to the compiler about what to expect - to enable it to grab the entire object graph. So add this to your code…

import java.io.Serializable;

public class Car implements Serializable{…}

import java.io.Serializable;

public class Carpool implements Serializable{…}

Car.java

Carpool.java

Page 5: cs121 week11 spring09 - SEIDENBERG SCHOOL OF CSIScsis.pace.edu/~ogotel/teaching/cs121_week11_spring09_small.pdf · 5 CS121/IS223 Week 11, Slide 25 To serialize a car object, we invoke

5

CS121/IS223 Week 11, Slide 25

To serialize a car object, we invoke the writeObject method of the ObjectOutputStream - basically, this would take all the state info out of your program and store it to a file at the end of an interactive session - cool! carpool is our collection of cars, salespeople is our collection of sales people … we would serialize those classes too! Use this canned code for now.

MyDriverClass.java

CS121/IS223 Week 11, Slide 26

To deserialize a car object, we invoke the readObject method of the ObjectInputStream - basically, this would put all the state info back into your program when you start up a session again - cool!

File to read objects from

Use Scanner, not Keyboard! MyDriverClass.java

CS121/IS223 Week 11, Slide 27

What is an Enumerated Type?

•  Establishes all possible values of a variable of that type by listing them all

enum Semester {fall, spring, summerI, summerII};

•  Semester currentSemester would declare a variable that is limited in the values it can hold to the 4 given above

•  currentSemester = Semester.fall would initialise the variable to have the value of fall

Was new to Java 5.0

CS121/IS223 Week 11, Slide 28

Example (from the text)

public class IceCream{ enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee, rockyRoad, mintChocolateChip, cookieDough}

public static void main (String[] args) { Flavor cone1, cone2, cone3;

cone1 = Flavor.rockyRoad; cone2 = Flavor.chocolate;

System.out.println ("cone1 value: " + cone1); System.out.println ("cone1 ordinal: " + cone1.ordinal()); System.out.println ("cone1 name: " + cone1.name());

System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name());

cone3 = cone1;

System.out.println (); System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); } }

CS121/IS223 Week 11, Slide 29

Autoboxing & Unboxing

•  Autoboxing automatically converts a primitive value to corresponding wrapper object

Integer obj1; int num1=42; obj1=num1;

•  Unboxing automatically extracts the primitive type

Integer obj2=new Integer(42); int num2; num2=obj2;

Was new to Java 5.0

Err…why do this? Well, remember that primitives and class types and handled differently…sometime we want to treat them similarly (say to store them in an ArrayList)

CS121/IS223 Week 11, Slide 30

NumberFormat EG - useful? (from the text)

import java.util.Scanner; import java.text.NumberFormat;

public class Purchase{ public static void main (String[] args) { final double TAX_RATE = 0.06; // 6% sales tax int quantity; double subtotal, tax, totalCost, unitPrice; Scanner scan = new Scanner (System.in);

NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); NumberFormat fmt2 = NumberFormat.getPercentInstance();

System.out.print ("Enter the quantity: "); quantity = scan.nextInt(); System.out.print ("Enter the unit price: "); unitPrice = scan.nextDouble(); subtotal = quantity * unitPrice; tax = subtotal * TAX_RATE; totalCost = subtotal + tax;

// Print output with appropriate formatting System.out.println ("Subtotal: " + fmt1.format(subtotal)); System.out.println ("Tax: " + fmt1.format(tax) + " at " + fmt2.format(TAX_RATE)); System.out.println ("Total: " + fmt1.format(totalCost)); } }

Page 6: cs121 week11 spring09 - SEIDENBERG SCHOOL OF CSIScsis.pace.edu/~ogotel/teaching/cs121_week11_spring09_small.pdf · 5 CS121/IS223 Week 11, Slide 25 To serialize a car object, we invoke

6

CS121/IS223 Week 11, Slide 31

Key Points

•  When you create an array of objects, you need to create the array & then all the objects that are to be stored in it - put methods that work on the collection in this collection class, not in the base object class

•  The ArrayList offers an alternative collection class if you need to store different types of object in the same place or if you have collections of variable size it is great – and an Iterator object is a neat way to pass through its elements

•  An interface is a set of methods an object makes available to other objects – check out Iterator

Explore the Java Collections API CS121/IS223 Week 11, Slide 32

To Do…

•  Finish Chapter 6 (ed 3) or Chapter 7 (ed 4+) – not GUIs

•  Work on the lab questions (make sure you do the go shopping question in lab2). Also work with the CD program handed out in class

•  If you want extra practice – please try programming projects 6.7, 6.9, 6.10 & 6.11 (ed 3) or 7.6, 7.7, 7.10 & 7.11 (ed 4+) – I have also posted all the text lab manuals on my website and reminded you to download code from the textbook. Remember to use me & the tutors… don’t get stuck!

•  Go through the lecture slides again & ask me if you have any questions

Work on your project – start designing

CS121/IS223 Week 11, Slide 33

Coming Up Next

•  NO CLASS ON THURSDAY 16 APRIL – WORK ON THE LABS

***

•  NEXT? Learning about how objects are really handled … object reference variables…

•  Fully fledged OO design and programming example to help bring things so far together, assist you with your project & prepare you for the final exam

•  There may be a project clinic and exam practice session set up for the nervous/anxious :-) -- so let me know if you would like this