csse221: software dev. honors day 12

23
CSSE221: Software Dev. Honors CSSE221: Software Dev. Honors Day 12 Day 12 Announcements Announcements No baby yet… No baby yet… Fifteen done. Fifteen done. Please read Class Announcements forum. Info Please read Class Announcements forum. Info about submitting IEPs there. about submitting IEPs there. New “late day” policy: New “late day” policy: You get 2 “late days” over the course of the term You get 2 “late days” over the course of the term that each give you a 24-hour extension that each give you a 24-hour extension The burden of turning in an assignment on a non- The burden of turning in an assignment on a non- class day is on you. class day is on you. You may earn late days for later use by turning in You may earn late days for later use by turning in the assignment a day early. the assignment a day early. You may use only 1 late day (or earn 1 early day) You may use only 1 late day (or earn 1 early day) per assignment per assignment Some restrictions apply (like right before an exam) Some restrictions apply (like right before an exam) I’ll allow this to be retroactive to any assignment I’ll allow this to be retroactive to any assignment you tried to submit late or thought about doing; you tried to submit late or thought about doing; just resubmit it on Thursday and I’ll enter the just resubmit it on Thursday and I’ll enter the grade. grade.

Upload: krikor

Post on 28-Jan-2016

40 views

Category:

Documents


0 download

DESCRIPTION

CSSE221: Software Dev. Honors Day 12. Announcements No baby yet… Fifteen done. Please read Class Announcements forum. Info about submitting IEPs there. New “late day” policy: You get 2 “late days” over the course of the term that each give you a 24-hour extension - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: CSSE221: Software Dev. Honors Day 12

CSSE221: Software Dev. Honors CSSE221: Software Dev. Honors Day 12Day 12 AnnouncementsAnnouncements

No baby yet…No baby yet… Fifteen done.Fifteen done. Please read Class Announcements forum. Info Please read Class Announcements forum. Info

about submitting IEPs there. about submitting IEPs there.

New “late day” policy:New “late day” policy: You get 2 “late days” over the course of the term that You get 2 “late days” over the course of the term that

each give you a 24-hour extensioneach give you a 24-hour extension The burden of turning in an assignment on a non-class The burden of turning in an assignment on a non-class

day is on you.day is on you. You may earn late days for later use by turning in the You may earn late days for later use by turning in the

assignment a day early. assignment a day early. You may use only 1 late day (or earn 1 early day) per You may use only 1 late day (or earn 1 early day) per

assignmentassignment Some restrictions apply (like right before an exam)Some restrictions apply (like right before an exam) I’ll allow this to be retroactive to any assignment you I’ll allow this to be retroactive to any assignment you

tried to submit late or thought about doing; just tried to submit late or thought about doing; just resubmit it on Thursday and I’ll enter the grade.resubmit it on Thursday and I’ll enter the grade.

Page 2: CSSE221: Software Dev. Honors Day 12

Research questionnaireResearch questionnaire

Page 3: CSSE221: Software Dev. Honors Day 12

This week: This week: CarsTrucksTrainsCarsTrucksTrains

Monday:Monday: Project workdayProject workday

Tuesday:Tuesday: Generics (capsule)Generics (capsule) IteratorsIterators

Thursday:Thursday: Lists (capsule)Lists (capsule) Implementation of linked lists Implementation of linked lists

Page 4: CSSE221: Software Dev. Honors Day 12

GenericsGenerics

We really want our algorithms to We really want our algorithms to operate on operate on any type of dataany type of data, , without having to re-write the whole without having to re-write the whole method.method.

In Java, we can do this two ways:In Java, we can do this two ways: Use inheritance (pre-Java 1.5, a bit Use inheritance (pre-Java 1.5, a bit

clunky)clunky) Use Use Generics Generics (newer, nicer)(newer, nicer)

Page 5: CSSE221: Software Dev. Honors Day 12

Using Inheritance Using Inheritance ArrayList list = new ArrayList();ArrayList list = new ArrayList();list.add(3); list.add(3); list.add("hello");list.add("hello");int num = list.get(0); // doesn’t workint num = list.get(0); // doesn’t workint num = (Integer)list.get(0);int num = (Integer)list.get(0);

Problems/concerns?Problems/concerns? We don’t have control over what goes into the We don’t have control over what goes into the

listlist Typecasting is a pain (and since we don’t have Typecasting is a pain (and since we don’t have

control, then we have to check for compatibility control, then we have to check for compatibility using instanceof to avoid ClassCastExceptionsusing instanceof to avoid ClassCastExceptions

Note: in Java 1.4, it was even worse…Note: in Java 1.4, it was even worse…

ArrayList list = new ArrayList();ArrayList list = new ArrayList();list.add(new Integer(3)); // 3 needs to be boxedlist.add(new Integer(3)); // 3 needs to be boxedlist.add("hello");list.add("hello");int num = list.get(0); // doesn’t workint num = list.get(0); // doesn’t workInteger temp = (Integer)list.get(0);Integer temp = (Integer)list.get(0);int num = temp.intValue(); // unboxingint num = temp.intValue(); // unboxing

Page 6: CSSE221: Software Dev. Honors Day 12

Using GenericsUsing Generics

ArrayList<Integer> list = ArrayList<Integer> list =

new ArrayList<Integer>();new ArrayList<Integer>();

list.add(3);list.add(3);

list.add(“hello”); // invalidlist.add(“hello”); // invalid

int num = list.get(0); // works!int num = list.get(0); // works!

Solves both those problems!Solves both those problems! We have control over the types of what We have control over the types of what

goes into the listgoes into the list No typecasting neededNo typecasting needed

Page 7: CSSE221: Software Dev. Honors Day 12

Creating code with Creating code with GenericsGenerics

To use generics, use the type in a parameter.To use generics, use the type in a parameter. Example showing:Example showing:

The use of a type in a classThe use of a type in a class Various places where the type parameter can be used:Various places where the type parameter can be used:

public class SomeClass<E> { public class SomeClass<E> { public E someMethod(E param) {public E someMethod(E param) {

E retValue = 2 * param;E retValue = 2 * param;return retValue;return retValue;

}}……

}}

Unfortunately, this example doesn’t work, since Unfortunately, this example doesn’t work, since we can’t multiply 2 by an unknown, possibly non-we can’t multiply 2 by an unknown, possibly non-numeric type.numeric type.

Page 8: CSSE221: Software Dev. Honors Day 12

DemoDemo

Page 9: CSSE221: Software Dev. Honors Day 12

Going furtherGoing further What if I have a method that operates on an What if I have a method that operates on an

ArrayList of Vehicles, but I want to pass an ArrayList of Vehicles, but I want to pass an ArrayList of Trucks?ArrayList of Trucks?

Intuitively, this should work, but Java doesn’t Intuitively, this should work, but Java doesn’t allow it, since it couldn’t catch errors until allow it, since it couldn’t catch errors until runtime.runtime.

Solution? In the method declaration, use Solution? In the method declaration, use type type boundsbounds with with wildcardswildcards::

public void public void processVehicle(ArrayList<? extends Vehicle> list) processVehicle(ArrayList<? extends Vehicle> list) {{ for (Vehicle v : list) { … }for (Vehicle v : list) { … }

}}

Page 10: CSSE221: Software Dev. Honors Day 12

Yet further and messier-Yet further and messier-lookinglooking

Consider Consider static E findMedian(E[] array)static E findMedian(E[] array)

Takes an array of type E, returns a value of that Takes an array of type E, returns a value of that typetype

But we need to restrict the generics to Comparable But we need to restrict the generics to Comparable types only (because we need types only (because we need compareTocompareTo). Use ). Use type type boundsbounds::

static <E extends Comparable> E findMedian(E[] array)static <E extends Comparable> E findMedian(E[] array)

But Comparable is generic:But Comparable is generic:static <E extends Comparable<E>> E findMedian(E[] array)static <E extends Comparable<E>> E findMedian(E[] array)

To enforce that E is Comparable, use To enforce that E is Comparable, use static <E extends Comparable<? super E>> E findMedian(E[] array)static <E extends Comparable<? super E>> E findMedian(E[] array)

If Vehicles were Comparable, then E could be Truck.If Vehicles were Comparable, then E could be Truck.

Then ? would be VehicleThen ? would be Vehicle

Page 11: CSSE221: Software Dev. Honors Day 12

Type erasureType erasure

At compile time, the generics are At compile time, the generics are replaced with the types usedreplaced with the types used

If there are bounds, it uses them and If there are bounds, it uses them and inserts the proper castsinserts the proper casts

Page 12: CSSE221: Software Dev. Honors Day 12

Some LimitationsSome Limitations Can’t use primitives as typesCan’t use primitives as types

No int, need to use IntegerNo int, need to use Integer Can’t instantiate a type: E foo = new E();Can’t instantiate a type: E foo = new E();

What is E? It could even be an abstract What is E? It could even be an abstract class; this wouldn’t make sense!class; this wouldn’t make sense!

Can’t make generic arrays: E[] ar = new Can’t make generic arrays: E[] ar = new E[17];E[17]; Naïve solution: use typecasts:Naïve solution: use typecasts:

E[] ar = (E[])(new Object[17])E[] ar = (E[])(new Object[17]) This gives a compiler warningThis gives a compiler warning

Better solution: use ArrayList<E>Better solution: use ArrayList<E>

Page 13: CSSE221: Software Dev. Honors Day 12

BreakBreak

Pass in quizzes (questions 1 and 2); Pass in quizzes (questions 1 and 2); I’ll use a different quiz for the I’ll use a different quiz for the second half.second half.

Page 14: CSSE221: Software Dev. Honors Day 12

Intro to Data StructuresIntro to Data Structures

Page 15: CSSE221: Software Dev. Honors Day 12

Data Structures and the Data Structures and the Java Collections Java Collections

FrameworkFramework What is data?What is data? What do we mean by "structure"What do we mean by "structure"

A data typeA data type But what But what isis a data type, really? a data type, really?

An interpretation of the bitsAn interpretation of the bits An An interpretationinterpretation is basically a set of operations. is basically a set of operations. The interpretation may be provided by the The interpretation may be provided by the

hardware, as for hardware, as for intint and and doubledouble types, or by types, or by software, as for the software, as for the java.math.BigIntegerjava.math.BigInteger type. type.

Or by software with much assistance from the Or by software with much assistance from the hardware, as for the hardware, as for the java.lang.Arrayjava.lang.Array type. type.

Page 16: CSSE221: Software Dev. Honors Day 12

Some basic data Some basic data structuresstructures Array (1D, 2D, …)Array (1D, 2D, …)

StackStack QueueQueue ListList

ArrayListArrayList LinkedListLinkedList

SetSet MultiSetMultiSet Map Map (a.k.a. table, (a.k.a. table,

dictionary)dictionary) HashMapHashMap TreeMapTreeMap

PriorityQueuePriorityQueue TreeTree GraphGraph NetworkNetwork

What is "special" about each data type?

What is each used for?

What can you say about time required foradding an element?removing an element?Finding an element?

You should know these, inside and out, by the end of CSSE230.

Page 17: CSSE221: Software Dev. Honors Day 12

Specifying an ADT in Specifying an ADT in JavaJava

The main Java tool for specifying an ADT is …The main Java tool for specifying an ADT is … … … an interface:an interface:

Some important methods from this interface:Some important methods from this interface:

Factory method

Page 18: CSSE221: Software Dev. Honors Day 12

IteratorsIterators

Consider a loop to fund the sum of Consider a loop to fund the sum of each element in an array:each element in an array:

for (int i = 0; i < ar.length; i++) {for (int i = 0; i < ar.length; i++) {

sum += ar[i];sum += ar[i];

}}

We want to generalize this beyond We want to generalize this beyond arraysarrays

Page 19: CSSE221: Software Dev. Honors Day 12

What's an iterator?What's an iterator? More specifically, what is a More specifically, what is a

jjava.util.Iteratorava.util.Iterator?? It's an interface:It's an interface: interface java.util.Iterator<E>interface java.util.Iterator<E> with the following methods:with the following methods:

We create a new concrete instance of an iterator, but We create a new concrete instance of an iterator, but use an interface return type (using polymorphism). use an interface return type (using polymorphism). This is what a This is what a factory method factory method does.does.

The advantage is that if we change the type of The advantage is that if we change the type of collection used in main(), then we don’t have to collection used in main(), then we don’t have to change the iterator type.change the iterator type.

Page 20: CSSE221: Software Dev. Honors Day 12

Example: Using an IteratorExample: Using an Iteratorag is a Collection object.

Using Java 1.5’s “foreach” construct:

Note that the Java compiler essentially translates the latter code into the former.

Page 21: CSSE221: Software Dev. Honors Day 12

What's an iterator?What's an iterator? More specifically, what is a More specifically, what is a

jjava.util.Iteratorava.util.Iterator?? It's an interface:It's an interface: interface java.util.Iterator<E>interface java.util.Iterator<E> with the following methods:with the following methods:

Why do iterators have their own Why do iterators have their own remove remove method, separate from the Collections’ method, separate from the Collections’ removeremove??

Page 22: CSSE221: Software Dev. Honors Day 12

Sort and Binary Sort and Binary SearchSearch

The The java.util.Arraysjava.util.Arrays class provides static methods for class provides static methods for sorting and doing binary search on arrays. sorting and doing binary search on arrays. Examples:Examples:

Page 23: CSSE221: Software Dev. Honors Day 12

Sort and Binary SearchSort and Binary Search

TheThe java.util.Collectionsjava.util.Collections class provides similar static methods class provides similar static methods for sorting and doing binary search for sorting and doing binary search on on CollectionCollections. Specifically s. Specifically ListLists. s.

Look up the details in the Look up the details in the documentation.documentation.