Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Size: px
Start display at page:

Download "Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha"

Transcription

1 Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide set Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha Read the first 5 sections of this tutorial Second tutorial by Sun is optional Java Generics and Collections by M. Naftalin and P. Wadler is a comprehensive reference (PDF available on the Internet) Read the first two chapters of this book if you want Break around 11:45am 1

2 Generic types Generics allow you to abstract over types. Commonly used in container types, e.g., in a Collection type. Example without generics: ArrayList u = new ArrayList(); u.add(new Point(2,3)); Point p = (Point)a.get(0); The type cast is annoying but necessary; The programmer knows what type of object has been placed into the list, but the compiler can only guarantee that an Object will be returned, thus the need for the type cast. Compiler cannot check that the cast is correct at compile-time, since it would not know what type of objects will be placed in it later. Inconvenient and unsafe, could fail at runtime. 2

3 Generic types (cont.) Example with generics: ArrayList<Point> u = new ArrayList<Point>(); u.add(new Point(2,3)); Point p = a.get(0); No need to type cast anymore! Compiler can now check the type correctness at compile-time because it knows that the list is to hold only Point objects Generics provide a way to communicate T, Point here, the type of elements in a collection, to the compiler. Compiler can check that you have used the collection consistently. Result: safer and more-efficient code. 3

4 Raw ArrayLists Creating a raw ArrayList: ArrayList al = new ArrayList(); Accessing a raw ArrayList: Note: this will cause a warning saying you re using the raw unsafe version when you try to add an object to it later. boolean add(object obj) Object set(int index, Object obj) Object get(int index) Why is Object used as a parameter here? 4

5 Motivation for generics Using Object as the parameter type means you can put any object into an ArrayList Seems useful but it s also a source of problems Can t check the type at compile time Suppose we want an ArrayList of Strings: ArrayList al = new ArrayList(); al.add(new String( Apple )); String as = (String)al.get(0); // need typecast al.add(new Integer(43)); // OK String as = (String)al.get(1); // runtime error! 5

6 Motivation for generics (cont.) Goal: detect type errors early at compile-time (as opposed to late at runtime) One solution is create specialized collection classes: one for Strings, another one for a different type, etc. ArrayListString, ArrayListYourObj, etc. This solution gives you type checking during compilation but at the undesirable expense of a lot of essentially identical code 6

7 Generics programming A solution for dealing with these kinds of type errors without code replication is generic programming - a way to write reusable generic type-safe code The String ArrayList example redone using generics: type parameter ArrayList<String> al = new ArrayList<String>(); al.add(new String( Apple )); String as = al.get(0); // no cast needed! al.add(new Integer(43)); // compile-time error, cool! 7

8 Generic types A generic type allows us to use a placeholder instead of an actual class in the definition of a class or interface Example: public class MyClass<T> {... Identifier T represents a class type within the definition of MyClass Can be any identifier but a single capital letter, e.g., T or E, is usually used for each type 8

9 Ex: Generic SingleItem class public class SingleItem<T> { private T item; SingleItem(T item) { // Constructor does not need <> this.item = item; public T getitem() { return(item); public void setitem(t item) { this.item = item; 9

10 Ex: Generic DoubleItem class public class DoubleItem <K,V> { private K item1; private V item2; // Key-Value pair DoubleItem (K item1, V item2) { this.item1 = item1; this.item2 = item2; K getitem1(){ return item1; V getitem2(){ return item2; 10

11 Instantiating a generic class SingleItem<String> si = new SingleItem<String>() or: SingleItem<String> si = new SingleItem<>(); DoubleItem<String,Integer> di = new DoubleItem<>(); Notice the use of the wrapper class Integer primitive types cannot be used directly as types for generic classes 11

12 Restricting type parameters Suppose I want my SingleItem class to only allow the class Foo and it s subtypes, e.g., SubFoo. Here s the heading for the new class definition: public class SingleItem<T extends Foo> {... Now I can do the following when instantiating a SingleItem: or SingleItem<Foo> item1 = new SingleItem<>(); SingleItem<SubFoo> item1 = new SingleItem<>(); 12

13 Generic methods In addition to writing generic data structures (classes), we can also write generic methods Why write generic methods? Similar to generic classes, we want to avoid creating many nearly-identical methods that only differ by the class type it operates on Let s look at a non-generic method and then convert it to generic 13

14 Generic classes as method parameters Suppose we have a method signature as follows: mymethod(arraylist<foo> mylist) {... Foo SubFoo Can I pass in a reference to ArrayList<SubFoo> instead? You might think so... but you can t! ArrayList<SubFoo> is not a subtype of ArrayList<Foo> even though SubFoo is a subclass of Foo. 14

15 Generic classes as method parameters (cont.) Instead, consider a method declared as follows: mymethod(arraylist<? extends Foo> mylist ) {... The notation <? extends Foo> means mymethod is expecting an ArrayList whose type parameter is a Foo or a subclass of Foo Now we can pass in a reference to ArrayList<Foo> or ArrayList<SubFoo> Formally, this is known as a bounded wildcard type You can also use <? super Foo> to indicate that a method expects a type parameter of Foo or a superclass of Foo. 15

16 Non-generic example // returns the number of times item occurs in list public static int count(string[] list, String item){ int c = 0; if (item == null) { for (String x : list) if (x == null) c++; else { for (String x : list ) if (item.equals(x)) // x.equals(item)? c++; return c; 16

17 Generic example // returns number of times item occurs in list of generic type T public static <T> int count(t[] list, T item){ int c = 0; if (item == null) { for (T x : list) if (x == null) c++; else { for (T x : list) if (item.equals(x)) c++; return c; 17

18 Generic insertion sort (v1) When writing a generic sort method, we need to use the compareto method so we need to be able say that we can only accept types that have implemented the Comparable<T> interface public static <T extends Comparable<T>> void isort(t[] a) { for (int i = 1; i < a.length; i++) { for (int j = i; j > 0; j--) { if (a[j - 1].compareTo(a[j]) > 0) { T temp = a[j - 1]; a[j - 1] = a[j]; a[j] = temp; 18

19 Generic insertion sort (v2) When writing a generic sort method, we need to use the compareto method so we need to be able say that we can only accept types that have implemented the Comparable<T> interface public class InsertionSort<T extends Comparable<T>> { public static void isort(t[] a) { for (int i = 1; i < a.length; i++) { T tmp = a[i]; for (int j = i; j>0 && a[j-1].compareto(tmp)>0; j--) { a[j] = a[j-1]; a[j] = tmp; 19

20 More examples (be sure to read!) See Generic.java Point.java Point3.java See Generic2.java (be sure to read the comments in this file) 20

21 Summary: Why generics? Safer code type violations caught early at compile-time type more specific to the needs Easier to read (in some cases) the type of the data contained in a data structure is clear ugly casts are not needed Reusable object-oriented code instead of type-specific code 21

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList: Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

Generalized Code. Fall 2011 (Honors) 2

Generalized Code. Fall 2011 (Honors) 2 CMSC 202H Generics Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using base classes is general, but restricted to a single class hierarchy

More information

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Ad hoc-polymorphism Outline Method overloading Sub-type Polymorphism Method overriding Dynamic

More information

Objects and Iterators

Objects and Iterators Objects and Iterators Can We Have Data Structures With Generic Types? What s in a Bag? All our implementations of collections so far allowed for one data type for the entire collection To accommodate a

More information

Primitive Java Generic Class

Primitive Java Generic Class Primitive Java Generic Class 1 A buffer pool is a data structure that caches records retrieved from a disk file, in order to improve an application's performance. Typically, the pool stores some sort of

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 James Wilcox / Winter 2016 Hi, I m James! Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping

More information

CSE 331. Generics (Parametric Polymorphism)

CSE 331. Generics (Parametric Polymorphism) CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/ 1 Parametric polymorphism

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 19 19:36:29 2017 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10. CS61B Lecture #23 Announcements: Josh s office hours are now back in his office. HW6 now due Saturday. Partial solar eclipse tomorrow, starting at 1:52PM. Next one in August, 2017. See http://www.timeanddate.com/eclipse/list.html

More information

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun Announcements Project 1 spec and code is available on the course website. Due July 15 th. Start early! Midterm I is next Wed in

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2 CSE 331 Software Design and Implementation Lecture 14 Generics 2 Zach Tatlock / Spring 2018 Big picture Last time: Generics intro Subtyping and Generics Using bounds for more flexible subtyping Using wildcards

More information

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1 CS61B Lecture #25: Java Generics Last modified: Thu Oct 18 21:04:53 2018 CS61B: Lecture #25 1 The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects.

More information

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal Version date:

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal  Version date: Java Brand Generics Advanced Topics in Java Khalid Azim Mughal khalid@ii.uib.no http://www.ii.uib.no/~khalid/atij/ Version date: 2005-03-03 Khalid Azim Mughal Java Brand Generics 1/40 Overview Introduction

More information

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism Lecture Outline Parametric Polymorphism and Java Generics Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping. Wildcards

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10. CS61B Lecture #24 Today: Java support for generic programming Readings for today: A Java Reference, Chapter 10. Readings for Monday: Data Structures, 6.4. Last modified: Fri Oct 19 19:33:03 2012 CS61B:

More information

On the Algorithm for Specializing Java Programs with Generic Types

On the Algorithm for Specializing Java Programs with Generic Types On the Algorithm for Specializing Java Programs with Generic Types Daniel Selifonov, Nathan Dahlberg, Elena Machkasova Computer Science Discipline University of Minnesota Morris Morris MN, 56267 selif004,dahlb061,elenam@umn.edu

More information

CMSC 341. Nilanjan Banerjee

CMSC 341. Nilanjan Banerjee CMSC 341 Nilanjan Banerjee http://www.csee.umbc.edu/~nilanb/teaching/341/ Announcements Just when you thought Shawn was going to teach this course! On a serious note: register on Piazza I like my classes

More information

Big O & ArrayList Fall 2018 Margaret Reid-Miller

Big O & ArrayList Fall 2018 Margaret Reid-Miller Big O & ArrayList 15-121 Fall 2018 Margaret Reid-Miller Today Exam 1: Thursday, Oct 4, 2018 Exam 2 date: Currently Thur. Oct 25 th Move to Tues Oct 30 or Thur Nov 1? (Withdraw deadline Tues Nov 6.) Homework

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Autumn 2013 Generics (Polymorphism) (Slides by Mike Ernst and David Notkin) 1 Varieties of abstraction Abstraction over computation: procedures int

More information

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5, Informatik II Tutorial 6 Mihai Bâce mihai.bace@inf.ethz.ch 05.04.2017 Mihai Bâce April 5, 2017 1 Overview Debriefing Exercise 5 Briefing Exercise 6 Mihai Bâce April 5, 2017 2 U05 Some Hints Variables &

More information

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Announcements. Java Graphics. Exceptions. Java Odds & Ends Java Odds & Ends Lecture 25 CS211 Fall 2005 Final Exam Wednesday, 12/14 9:00-11:30am Uris Aud Review Session Sunday, 12/11 1:00-2:30pm Kimball B11 Check your final exam schedule! Announcements For exam

More information

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007 Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007 (These notes are very rough, and differ somewhat from what I presented in class; I am posting them here to supplemental

More information

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages Preliminaries II 1 Agenda Objects and classes Encapsulation and information hiding Documentation Packages Inheritance Polymorphism Implementation of inheritance in Java Abstract classes Interfaces Generics

More information

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit. Name CS 110 Practice Final Exam originally from Winter, 2003 Instructions: closed books, closed notes, open minds, 3 hour time limit. There are 4 sections for a total of 49 points. Part I: Basic Concepts,

More information

Exercise 8 Parametric polymorphism November 18, 2016

Exercise 8 Parametric polymorphism November 18, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 8 Parametric polymorphism November 18, 2016 Task 1 Consider the following Scala classes: class A class B extends A class P1[+T] class P2[T

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Parametric polymorphism and Generics

Parametric polymorphism and Generics Parametric polymorphism and Generics Today s Lecture Outline Parametric polymorphism Java generics Declaring and instantiating generics Bounded types: restricting instantiations Generics and subtyping.

More information

CS 251 Intermediate Programming Inheritance

CS 251 Intermediate Programming Inheritance CS 251 Intermediate Programming Inheritance Brooke Chenoweth University of New Mexico Spring 2018 Inheritance We don t inherit the earth from our parents, We only borrow it from our children. What is inheritance?

More information

Java 5 New Language Features

Java 5 New Language Features Java 5 New Language Features Ing. Jeroen Boydens, BLIN prof dr. ir. Eric Steegmans http://users.khbo.be/peuteman/java5/ Enterprise Programming Last session. Jeroen Boydens 1. JDK v1.4: assert 2. Generics

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal APCS A Midterm Review You will have a copy of the one page Java Quick Reference sheet. This is the same reference that will be available to you when you take the AP Computer Science exam. 1. n bits can

More information

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java. JAVA GENERICS Lecture CS110 Fall 018 Photo credit: Andrew Kennedy Java Collections Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob */ boolean

More information

Inheritance. Improving Structure with Inheritance. Dr. Siobhán Drohan Mairead Meagher. Produced by:

Inheritance. Improving Structure with Inheritance. Dr. Siobhán Drohan Mairead Meagher. Produced by: Inheritance Improving Structure with Inheritance Produced by: Dr. Siobhán Drohan Mairead Meagher Department of Computing and Mathematics http://www.wit.ie/ Lectures and Labs This weeks lectures and labs

More information

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø

More information

Informatik II (D-ITET) Tutorial 6

Informatik II (D-ITET) Tutorial 6 Informatik II (D-ITET) Tutorial 6 TA: Marian George, E-mail: marian.george@inf.ethz.ch Distributed Systems Group, ETH Zürich Exercise Sheet 5: Solutions and Remarks Variables & Methods beginwithlowercase,

More information

Informatik II Tutorial 6. Subho Shankar Basu

Informatik II Tutorial 6. Subho Shankar Basu Informatik II Tutorial 6 Subho Shankar Basu subho.basu@inf.ethz.ch 06.04.2017 Overview Debriefing Exercise 5 Briefing Exercise 6 2 U05 Some Hints Variables & Methods beginwithlowercase, areverydescriptiveand

More information

APCS Unit 5 Exam. Assuming all four classes have a default constructor, which of the following statements would result in an error from the compiler?

APCS Unit 5 Exam. Assuming all four classes have a default constructor, which of the following statements would result in an error from the compiler? APCS Unit 5 Exam Name 1. Suppose we had a superclass called Fruit. The subclasses of this superclass are Apple, Orange, and Banana. Consider the following reference variable declarations. Fruit f; Banana

More information

Photo credit: Andrew Kennedy JAVA GENERICS

Photo credit: Andrew Kennedy JAVA GENERICS Photo credit: Andrew Kennedy JAVA GENERICS Lecture 17 CS2110 Spring 2017 Java Collections 2 Early versions of Java lacked generics interface Collection { /** Return true iff the collection contains ob

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018 CSE 331 Software Design and Implementation Lecture 14 Generics 1 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due Thursday Homework 6 due Thursday Midterm grades and feedback will

More information

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

CSE 331 Software Design and Implementation. Lecture 14 Generics 1 CSE 331 Software Design and Implementation Lecture 14 Generics 1 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due Thursday Homework 6 due Thursday Midterm grades and feedback will

More information

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments CMSC433, Spring 2004 Programming Language Technology and Paradigms Java Review Jeff Foster Feburary 3, 2004 Administrivia Reading: Liskov, ch 4, optional Eckel, ch 8, 9 Project 1 posted Part 2 was revised

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

CSE 326: Data Structures. Section notes, 4/9/2009

CSE 326: Data Structures. Section notes, 4/9/2009 CSE 326: Data Structures Java Generi ics & JUnit 4 Section notes, 4/9/2009 slides originally by Hal Perkins Type-Safe Containers Idea a class or interface can have a type parameter: public class Bag

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Generics and Type Parameters

Generics and Type Parameters Generics and Type Parameters Simple Generic Class Example you have already written: public class ArrayIterator implements Iterator { private T[] array; public ArrayIterator(T[] a) { this.array =

More information

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10 Generics Computer Science and Engineering College of Engineering The Ohio State University Lecture 10 A Simple Component Client-side view: Pencil interface Pencil { String tostring(); void setcolor(colors

More information

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation CSE 331 Software Design and Implementation Lecture 15 Generics 2 Announcements Leah Perlmutter / Summer 2018 Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

CSE 331 Software Design and Implementation. Lecture 15 Generics 2 CSE 331 Software Design and Implementation Lecture 15 Generics 2 Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 5 is due tomorrow Homework 6 due tomorrow Section tomorrow! Subtyping now

More information

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus Types Type checking What is a type? The notion varies from language to language Consensus A set of values A set of operations on those values Classes are one instantiation of the modern notion of type

More information

CS108, Stanford Handout #8. Java Generics

CS108, Stanford Handout #8. Java Generics CS108, Stanford Handout #8 Fall, 2007-08 Nick Parlante Java Generics Java generics (added in version 5) are a mixed bag. Some uses of generics are simple to understand and make the code cleaner. They are

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

Generics and Type Safety. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Generics and Type Safety. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Generics and Type Safety CS 180 Sunil Prabhakar Department of Computer Science Purdue University Dynamic Data Collections Already seen several examples of dynamic data Linked list, Stack, Queue, Trees

More information

CSE 8B Intro to CS: Java

CSE 8B Intro to CS: Java CSE 8B Intro to CS: Java Winter, 2006 March 7 (Day 17) ArrayList Generics Class that: works like a resizable array ArrayList Has a current capacity: if you add more elements, it ll allocate more space

More information

Collections Algorithms

Collections Algorithms Collections Algorithms 1 / 11 The Collections Framework A collection is an object that represents a group of objects. The collections framework allows different kinds of collections to be dealt with in

More information

Csci 102: Sample Exam

Csci 102: Sample Exam Csci 102: Sample Exam Duration: 65 minutes Name: NetID: Student to your left: Student to your right: DO NOT OPEN THIS EXAM UNTIL INSTRUCTED Instructions: Write your full name and your NetID on the front

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

Midterm Exam CS 251, Intermediate Programming March 12, 2014

Midterm Exam CS 251, Intermediate Programming March 12, 2014 Midterm Exam CS 251, Intermediate Programming March 12, 2014 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

COS 126 General Computer Science Spring Written Exam 1

COS 126 General Computer Science Spring Written Exam 1 COS 126 General Computer Science Spring 2017 Written Exam 1 This exam has 9 questions (including question 0) worth a total of 70 points. You have 50 minutes. Write all answers inside the designated spaces.

More information

Simple Sorting. Bubble Sort

Simple Sorting. Bubble Sort Simple Sorting Bryn Mawr College CS206 Intro to Data Structures Bubble Sort Start at the left end of the array and compare the first two elements. If the one on the right is bigger, you don t do anything;

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Sunday, Tuesday: 9:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming A programming

More information

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007 Advanced Topics in Java and on Security in Systems Effective Generics Eirik Eltvik 26 th of February 2007 Taking care when calling Legacy code Checks at compile-time is not always appropriate When? Legacy

More information

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban 15-440 Distributed Systems Recitation 1 Tamim Jabban Office Hours Office 1004 Tuesday: 9:30-11:59 AM Thursday: 10:30-11:59 AM Appointment: send an e-mail Open door policy Java: Object Oriented Programming

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Interface Abstract data types Version of January 26, 2013 Abstract These lecture notes are meant

More information

+ Abstract Data Types

+ Abstract Data Types Linked Lists Abstract Data Types An Abstract Data Type (ADT) is: a set of values a set of operations Sounds familiar, right? I gave a similar definition for a data structure. Abstract Data Types Abstract

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

Use of the ArrayList class

Use of the ArrayList class Use of the ArrayList class The ArrayList class is very similar to the Vector class. It also manages a collection of objects, and as the name indicates, does so with an array implementation. This is also

More information

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Java Generics -- an introduction Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Generics vs. Templates Templates in C++ are compiled into unique code based on the types passed

More information

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1

CMSC 433 Section 0101 Fall 2012 Midterm Exam #1 Name: CMSC 433 Section 0101 Fall 2012 Midterm Exam #1 Directions: Test is closed book, closed notes. Answer every question; write solutions in spaces provided. Use backs of pages for scratch work. Good

More information

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes Java Curriculum for AP Computer Science, Student Lesson A20 1 STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes INTRODUCTION:

More information

Announcements. Final exam. Course evaluations. No classes next week. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA. Wednesday November 28th

Announcements. Final exam. Course evaluations. No classes next week. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA. Wednesday November 28th Announcements Final exam Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA Course evaluations Wednesday November 28th No classes next week no lectures, labs, or recitations Happy Thanksgiving! 1 Generics

More information

Logistics. Final Exam on Friday at 3pm in CHEM 102

Logistics. Final Exam on Friday at 3pm in CHEM 102 Java Review Logistics Final Exam on Friday at 3pm in CHEM 102 What is a class? A class is primarily a description of objects, or instances, of that class A class contains one or more constructors to create

More information

Function Objects Exercise Generic Methods Searching (sequential, Binary, Interpolation) Abstract Data Types and Data Structures

Function Objects Exercise Generic Methods Searching (sequential, Binary, Interpolation) Abstract Data Types and Data Structures Function Objects Exercise Generic Methods Searching (sequential, Binary, Interpolation) Abstract Data Types and Data Structures Work on the exercise that you began Thursday for the first 15 minutes of

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Winter 2018 Generics UW CSE 331 Winter 2018 1 Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1

More information

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017 Task 1 In this question, we are in a nominal subtyping setting. Some languages have a special

More information

Generic classes & the Java Collections Framework. *Really* Reusable Code

Generic classes & the Java Collections Framework. *Really* Reusable Code Generic classes & the Java Collections Framework *Really* Reusable Code First, a bit of history Since Java version 5.0, Java has borrowed a page from C++ and offers a template mechanism, allowing programmers

More information

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2014 Name: This exam consists of 5 problems on the following 6 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet

More information

Object Oriented Programming: Based on slides from Skrien Chapter 2

Object Oriented Programming: Based on slides from Skrien Chapter 2 Object Oriented Programming: A Review Based on slides from Skrien Chapter 2 Object-Oriented Programming (OOP) Solution expressed as a set of communicating objects An object encapsulates the behavior and

More information

Outline of lecture. i219 Software Design Methodology 6. Object oriented programming language 3. Kazuhiro Ogata (JAIST)

Outline of lecture. i219 Software Design Methodology 6. Object oriented programming language 3. Kazuhiro Ogata (JAIST) i219 Software Design Methodology 6. Object oriented programming language 3 Kazuhiro Ogata (JAIST) Outline of lecture 2 Primitive wrapper class Generics Primitive wrapper class 3 For each primitive type,

More information

Lecture Notes Chapter #9 Summery. Inheritance

Lecture Notes Chapter #9 Summery. Inheritance Lecture Notes Chapter #9 Summery Inheritance Subclass inherits all members of its superclass except its constructors methods inherited from a superclass can overridden in the subclass o a method overrides

More information

Generics, Type Safety, and Dynamic Data Structures

Generics, Type Safety, and Dynamic Data Structures Generics, Type Safety, and Dynamic Data Structures 1 Reminders No classes, labs, recitations next week (gobble gobble) Consulting hours Monday only Project 8 (the final one!) is out start early Milestone

More information

Improving structure with inheritance. Main concepts to be covered. The DoME example. DoME objects. DoME classes. DoME object model

Improving structure with inheritance. Main concepts to be covered. The DoME example. DoME objects. DoME classes. DoME object model Improving structure with inheritance Main concepts to be covered Inheritance -- adding functionality to classes by extending them Subtyping, as in ArrayList Substitution: if you want a car, either

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

Java: exceptions and genericity

Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: exceptions and genericity Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Exceptions Exceptions

More information

Announcements/Follow-ups

Announcements/Follow-ups Announcements/Follow-ups Midterm #2 Friday Everything up to and including today Review section tomorrow Study set # 6 online answers posted later today P5 due next Tuesday A good way to study Style omit

More information

Lesson 43.. ArrayList

Lesson 43.. ArrayList Lesson 43.. ArrayList 43-1 You will recall from Lesson 42 the ArrayList is one of several classes that implement the List interface. As its name suggests, ArrayList also involves arrays. Basically, everything

More information

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Inheritance II Lecture 23, Thu Mar 30 2006 based on slides by Kurt Eiselt http://www.cs.ubc.ca/~tmm/courses/cpsc111-06-spr

More information

Generics. IRS W-9 Form

Generics. IRS W-9 Form Generics IRS W-9 Form Generics Generic class and methods. BNF notation Syntax Non-parametrized class: < class declaration > ::= "class" < identifier > ["extends" < type >] ["implements" < type list >]

More information

CMSC 132: Object-Oriented Programming II. Interface

CMSC 132: Object-Oriented Programming II. Interface CMSC 132: Object-Oriented Programming II Interface 1 Java Interfaces An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are Java's

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Computer Science II Data Structures

Computer Science II Data Structures Computer Science II Data Structures Instructor Sukumar Ghosh 201P Maclean Hall Office hours: 10:30 AM 12:00 PM Mondays and Fridays Course Webpage homepage.cs.uiowa.edu/~ghosh/2116.html Course Syllabus

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting Overview ITI 1121. Introduction to Computing II Rafael Falcon and Marcel Turcotte (with contributions from R. Holte) Electrical Engineering and Computer Science University of Ottawa Interface Abstract

More information

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented Table of Contents L01 - Introduction L02 - Strings Some Examples Reserved Characters Operations Immutability Equality Wrappers and Primitives Boxing/Unboxing Boxing Unboxing Formatting L03 - Input and

More information