Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types

Similar documents
Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

What are Generics? e.g. Generics, Generic Programming, Generic Types, Generic Methods

Java Generics -- an introduction. Based on

Generics. Chapter Contents

Principles of Computer Science

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Inheritance and Polymorphism

Distributed Systems Recitation 1. Tamim Jabban

Distributed Systems Recitation 1. Tamim Jabban

Collections, Maps and Generics

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

Advanced Programming Generics Collections

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Typing issues JAVA GENERICS. ! Parametric Polimorphism. ! Bounded Polymorphism. ! F- Bounded Polymorphism 10/28/13. Examples and Problems

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

Data Structures. BSc in Computer Science University of New York, Tirana. Assoc. Prof. Marenglen Biba 1-1

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

1.1. Annotations History Lesson - C/C++

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

Chapter 11 Inheritance and Polymorphism

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

Generics. CSE260, Computer Science B: Honors Stony Brook University

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

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

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

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

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

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

Generics method and class definitions which involve type parameters.

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

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

Parametric polymorphism and Generics

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

Software Engineering. Prof. Agostino Poggi

CS 61B Discussion 5: Inheritance II Fall 2018

CMSC 341. Nilanjan Banerjee

CSE 331 Software Design & Implementation

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s).

Grouping Objects (I)

CS108, Stanford Handout #8. Java Generics

Module 11. Collections and Iterators. Adapted from Absolute Java, Rose Williams, Binghamton University

Generics, Type Safety, and Dynamic Data Structures

Inheritance (Part 2) Notes Chapter 6

The collections interfaces

CITS2210 Object-Oriented Programming. Topic 9. Java: Generics

Java 5 New Language Features

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

generic programming alberto ferrari university of parma

Chapter 11 Inheritance and Polymorphism

Exercise 8 Parametric polymorphism November 18, 2016

Test Class A. public class A { private int x, y; public int getx() { return x; } public int gety() { return y; }

CSE 331. Generics (Parametric Polymorphism)

Data Structure. Recitation IV

COMP6700/2140 Generic Types

Generalized Code. Fall 2011 (Honors) 2

[TAP:AXETF] Inheritance

Java Programming Unit 8. Selected Java Collec5ons. Generics.

CMSC 202. Containers

CSE 331 Software Design & Implementation

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA

Create a Java project named week10

CSCE 314 Programming Languages

OOPSLA 2004, Vancouver

AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested.

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

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

Object-Oriented Programming More Inheritance

Grouping objects Lecture 7

CMSC 202H. Containers and Iterators

AP CS Unit 7: Interfaces. Programs

301AA - Advanced Programming [AP-2017]

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

To describe the Java Collections Framework. To use the Iterator interface to traverse a. To discover the Set interface, and know how

Coverage of Part 2. A Brief Introduction to Java for C++ Programmers: Part 2. import: using packages

301AA - Advanced Programming [AP-2017]

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

COMP 250. inheritance (cont.) interfaces abstract classes

Polymorphism (generics)

Arrays and ArrayLists. David Greenstein Monta Vista High School

EECS2030 Week 7 worksheet Tue Feb 28, 2017

Slides are adapted from the originals available at

Rules and syntax for inheritance. The boring stuff

Exercise 13 Self-Study Exercise Sheet

Software Practice 1 - OOP (3) API Access Control Review Packages Java API Documentation

#Students per correct answers

01. Which of the following statement describes dynamic resizing as is applies to the ArrayList class?

CMSC 202. Generics II

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

CSA 1019 Imperative and OO Programming

Generics and collections

Building Java Programs

Simple Sorting. Bubble Sort

COURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE

Transcription:

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types

generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to reuse the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.

Stronger type checks at compile time. Elimination of casts List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); When re-written to use generics, List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // no cast Enabling programmers to implement generic algorithms.

A generic type is a generic class or interface that is parameterized over types. public class Box { private Object object; public void set(object object) { this.object = object; public Object get() { return object; public class Box<T> { // T stands for "Type" private T t; public void set(t t) { this.t = t; public T get() { return t; Invoking and Instantiating a Generic Type Box<Integer> integerbox = new Box<Integer>(); Java SE 7 and later Box<Integer> integerbox = new Box<>(); //Integer type argument

Raw type : is the name of a generic class or interface without any type arguments. public class Box<T> { public void set(t t) { /*... */ //... Box<Integer> intbox = new Box<>(); Box rawbox = new Box(); rawbox.set(3); -- Box is the raw type of the generic type Box<T>. Compile: Note: C:\Users\Test\src\test\Box.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared.

public class Pair<K, V> { private K key; private V value; // Generic constructor public Pair(K key, V value) { this.key = key; this.value = value; // Generic methods public void setkey(k key) { this.key = key; public void setvalue(v value) { this.value = value; public K getkey() { return key; public V getvalue() { return value; public class Util { // Generic static method public static <K, V> boolean compare(pair<k, V> p1, Pair<K, V> p2) { return p1.getkey().equals(p2.getkey()) && p1.getvalue().equals(p2.getvalue()); Pair<Integer, String> p1 = new Pair<>(1, "apple"); Pair<Integer, String> p2 = new Pair<>(2, "pear"); boolean same = Util.compare(p1, p2);

To restrict the types that can be used as type arguments in a parameterized type public class Box<T extends Number> { // T stands for "Type" private T t; public void set(t t) { this.t = t; public T get() { return t; public class Test{ public static void main(string[] args) { Box <Integer> box1 = new Box<>(); Box <Double> box2 = new Box<>(); Box <String> box3 = new Box<>();

public class Box<T > { // T stands for "Type" private T t; public void set(t t) { this.t = t; public T get() { return t; Box<Object> box1 = new Box<Number>();//no Box<Object> box2 = new Box<Integer>(); //no Box<Number> box3 = new Box<Number>();//ok Box<Integer> box4 = new Box<Integer>();//ok Box<Number> box = new Box<Number>(); box.add(new Integer(10)); // OK box.add(new Double(10.1)); // OK

1. public class Box<T> { 2. private T t; 3. private List<T> list = new ArrayList<>();; 4. public void set(t t) { this.t = t; 5. public T get() { return t; 6. public void add(t elem){ 7. list.add(elem); 8. 9. public static void print(box<number> b){ 10. System.out.println(b.get()); 11. 12. public static void main(string[] args) { 13. Box <Number> box1 = new Box<>(); 14. box1.add(new Integer(3)); 15. box1.add(new Double(3.2)); 16. box1.print(box1); 17. 18. Box <Double> box2 = new Box<>(); 19. box1.print(box2); 20. 21.

use an upper bounded wildcard to relax the restrictions on a variable want to write a method that works on List<Integer>, List<Double>, and List<Number> Any subclasses include itself java.util.arraylist<e> +ArrayList() +add(o: E) : void +add(index: int, o: E) : void +clear(): void +contains(o: Object): boolean +get(index: int) : E +indexof(o: Object) : int +isempty(): boolean +lastindexof(o: Object) : int +remove(o: Object): boolean +size(): int +remove(index: int) : boolean +set(index: int, o: E) : E (b) ArrayList in JDK 1.5

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public class Test3 { public static void print(arraylist<? extends Animal> animals){ System.out.println(animals); public static void main(string[] args) { ArrayList<Dog> dogs = new ArrayList<Dog>(); dogs.add(new Dog()); dogs.add(new Dog()); ArrayList<Cat> cats = new ArrayList<Cat>(); cats.add(new Cat()); cats.add(new Cat()); animals.add(new Dog());//complie error, cannot add print(dogs); print(cats); สมาช กใน list ท ส งไปม type เป นต วเองหร อเป นล กหลาน Ok Animal, Dog, Cat แต add ไม ได 12

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import java.util.*; public class Test { public static void addanimals(arraylist<? super Dog> animals){ animals.add(new Dog());//ok public static void main(string[] args) { // make ArrayLists instead of arrays for Dog, Cat, Bird ArrayList<Dog> dogs = new ArrayList<Dog>(); dogs.add(new Dog()); dogs.add(new Dog()); ArrayList<Cat> cats = new ArrayList<Cat>(); cats.add(new Cat()); cats.add(new Cat()); ArrayList<Animal> ams = new ArrayList<Animal>(); ams.add(new Animal()); ams.add(new Animal()); addanimals(dogs); addanimals(ams); addanimals(cats);//compile error สมาช กใน list ท ส งไปม type เป นต วเองหร อ super class จะ OK Dog, Animal, Object และ add ได เฉพาะ type ของต วเอง add ได เฉพาะ Dog เท าน น 13

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.util.*; public class Test5 { public static void print(arraylist<object> list){ System.out.println(list); public static void main(string[] args) { ArrayList<Dog> dogs = new ArrayList<Dog>(); dogs.add(new Dog()); dogs.add(new Dog()); ArrayList<Cat> cats = new ArrayList<Cat>(); cats.add(new Cat()); cats.add(new Cat()); print(dogs); //no print(cats); //no 14

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 import java.util.*; public class Test5 { public static void print(arraylist<?> list){ System.out.println(list); // list.add(new Dog());//compile error // list.add(new Object());//compile error public static void main(string[] args) { ArrayList<Dog> dogs = new ArrayList<Dog>(); dogs.add(new Dog()); dogs.add(new Dog()); ArrayList<Cat> cats = new ArrayList<Cat>(); cats.add(new Cat()); cats.add(new Cat()); print(dogs); print(cats); ArrayList<Integer> num = new ArrayList<>(); num.add(2); num.add(3); print(num); 15

GenericStack<E> -elements: E[] -size: int +GenericStack() +GenericStack(initialCapacity: int) +getsize(): int +peek(): E +pop(): E +push(o: E): E +isempty(): boolean An array to store elements. The number of the elements in this stack. Creates an empty stack with default initial capacity 16. Creates an empty stack with the specified initial capacity. Returns the number of elements in this stack. Returns the top element in this stack. Returns and removes the top element in this stack. Adds a new element to the top of this stack. Return true if the stack is empty. GenericStack 16