Saint Petersburg, 2011 Java Lecture Generics. Quiz ArrayList lst = new ArrayList(); Collection c = lst; lst.add("one"); lst.add(“two"); lst.add(“three");

Slides:



Advertisements
Similar presentations
INF 212 ANALYSIS OF PROG. LANGS Type Systems Instructors: Crista Lopes Copyright © Instructors.
Advertisements

The Substitution Principle SWE 332 – Fall Liskov Substitution Principle In any client code, if subtype object is substituted for supertype object,
Java Review Interface, Casting, Generics, Iterator.
Wildcards in the Java™ Programming Language Neal Gafter with thanks to Mads Torgersen, University of Aarhus.
Java Generics.
ООП Классы – 2. Ссылки Ссылка – еще одно имя объекта. Используйте ссылки вместо указателя. Это более безопасно. Complex c(10,10); Complex c2& = c; c2+=10;
Особенности Java. Блок static static { } Создание и уничтожение объектов  new – создание объекта  finalyze()
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
Generic Programming David Rabinowitz. March 3rd, 2004 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
PHP как язык программирования. Типы данных логические величины int, integer – целые числа real, double, float – вещественные числа string – строки array.
Контейнеры. Сортировка  Метод sort()  Интерфейс Comparable метод int compareTo(Object o) вызов: Arrays.sort(a)  Интерфейс Comparator метод int compare(Object.
Lists Discussion F. Generics Tutorial (Ref: Gilad Baracha) ● Auto Boxing ● Erasure ● Sub Classes ● Unchecked Type cast ● Bounded Wildcards.
Creating Generic Classes. Introduction Java Generics were added to allow for type- safe collections and eliminate the need for burdensome, code-cluttering.
Generic Programming Amit Shabtay. March 3rd, 2004 Object Oriented Design Course 2 The Problem Assume we have a nice Stack implementation. Our stack receives.
Gruppe Grøn Effective Java Items: 4, 12, 20, 28 36, 44, 52, 60 1.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Java Generics and Subtyping Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
„Generics and collections”. Generics and collections Generics From JDK They are similar to C++ templates They allow to eliminate runtime exceptions.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Java Programming II 1 Generic Types and Inner Classes.
16 - Generics. 2 NOEA2009Java-kursus – Generics ”Generic” Programming in C#/Java (as it was until Summer 2005) All classes inherit from Object So we can.
Concordia University Department of Computer Science and Software Engineering Click to edit Master title style ADVANCED PROGRAMING PRACTICES Java generics.
ADSA: Subtypes/ Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce.
Java Generics.
Enter Title of Presentation Here Joshua Bloch Chief Java Architect
Effective Java: Generics Last Updated: Spring 2009.
Generics in.NET and C# Generics. ”Generic” Programming in C#/Java (as it was until Summer 2005) All classes inherit from Object So we can apply polymorphism.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
CSE 331 Software Design & Implementation Dan Grossman Winter 2014 Generics (Based on slides by Mike Ernst, David Notkin, Hal Perkins)
Object Oriented Programming Lecture 11: Polymorphism.
Generic Types  Recent release of Java added generics  Include type parameters in class definition  Like methods, parameters can change each time 
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Types in programming languages1 What are types, and why do we need them?
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
CMSC 330: Organization of Programming Languages Java Generics.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CSCE 314 Programming Languages Java Generics II Dr. Hyunyoung Lee 1.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
Polymorphism (generics) CSE 331 University of Washington.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION GENERICS/PARAMETRIC POLYMORPHISM Autumn 2011 We We Abstraction.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
Problem of the Day How can you make 16 right angles using 4 matchsticks WITHOUT breaking any of them?
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
1.Net programmingGenericsNOEA / 2009 Generics 11. Generics in.NET and C#
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
Question of the Day  Move one matchstick to produce a square.
James Wilcox / Winter 2016 CSE 331 Software Design and Implementation Lecture 14 Generics 2.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
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.
John Hurley Cal State LA
More Generics רובי בוים ומתי שמרת
Generics and Subtyping
null, true, and false are also reserved.
CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation
Generics (Parametric Polymorphism)
Java Generics Lecture 22 CS2110 – Fall 2018
CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation
More on Thread Safety CSE451 Andrew Whitaker.
Effective Java: 3rd Edition Generics
CSE 331 Software Design and Implementation
Generic Programming.
COMP204 Bernhard Pfahringer (with input from Robi Malik)
Presentation transcript:

Saint Petersburg, 2011 Java Lecture Generics

Quiz ArrayList lst = new ArrayList(); Collection c = lst; lst.add("one"); lst.add(“two"); lst.add(“three"); lst.remove(0); c.remove(0); System.out.println(lst.size()); System.out.println(c.size()); 2

Road to Generics  Класс - ящик для хранения других объектов class Box { private Object object; void add(Object object) { this.object = object; } Object get() { return object; } 3

Road to Generics  Класс - ящик для хранения других объектов class Box { private Object object; void add(Object object) { this.object = object; } Object get() { return object; }  При использовании необходимо кастовать к нужному типу, это небезопасно Box integerBox = new Box(); integerBox.add(new Integer(10)); Integer someInteger = (Integer) integerBox.get(); 4

Road to Generics  Класс - ящик для хранения других объектов class Box { private Object object; void add(Object object) { this.object = object; } Object get() { return object; }  При использовании необходимо кастовать к нужному типу, это небезопасно Box integerBox = new Box(); integerBox.add(new Integer(10)); integerBox.add(”10”); Integer someInteger = (Integer) integerBox.get(); //Exception!!! 5

Road to Generics  Можно защититься, но это неудобно: Box integerBox = new Box(); Object content = integerBox.get(); if (content instanceof Integer) { Integer someInteger = (Integer)integerBox.get(); System.out.println(someInteger + 5); } 6

Road to Generics  Можно защититься, но это неудобно: Box integerBox = new Box(); Object content = integerBox.get(); if (content instanceof Integer) { Integer someInteger = (Integer)integerBox.get(); System.out.println(someInteger + 5); } 7

Road to Generics  Generics: we can do it safe and clear! class Box { private T object; void add(T object) { this.object = object; } T get() { return object; } 8

Road to Generics  Generics: we can do it safe and clear! class Box { private T object; void add(T object) { this.object = object; } T get() { return object; }  Соответственно, использование изменится к лучшему: Box integerBox = new Box (); integerBox.add(new Integer(10)); Integer someInteger = integerBox.get(); 9

Generic classes  Generics: we can do it safe and clear! class Box { private T object; void add(T object) { this.object = object; } T get() { return object; }  Соответственно, использование изменится к лучшему: Box integerBox = new Box (); integerBox.add(new Integer(10)); integerBox.add(”10”); // Не компилируется Integer someInteger = integerBox.get(); String someInteger = integerBox.get(); // Не компилируется 10

Generic methods  Также можно объявлять generic методы: class Box { private T object; void add(T object) { this.object = object; } T get() { return object; } void inspect(U u) { System.out.println("U: " + u.getClass().getName()); } 11

Generic methods  Также можно объявлять generic методы: class Box { private T object; void add(T object) { this.object = object; } T get() { return object; } static void fillBoxes(U u, List > boxes) { for (Box box : boxes) { box.add(u); } Box. fillBoxes(42, new ArrayList >()); 12

Wildcards  Generic types are invariant  List не наследует List : Integer[] iArray = {1, 3, 2}; Object[] oArray = iArray; // OK List iList = new ArrayList (); List oList = iList; // Не компилируется 13

Wildcards  Generic types are invariant  List не наследует List : Integer[] iArray = {1, 3, 2}; Object[] oArray = iArray; List iList = new ArrayList (); List oList = iList; //Не компилируется  Чтобы решить эту проблему, можно использовать wildcard:  – любой класс  – ограничение снизу: все классы, которые являются наследниками Number  – ограничение сверху: все классы, являющиеся родителями класса Number 14

 Возможны множествовариантов инициализации: List list1 = new ArrayList (); List list2 = new ArrayList (); List list3 = new ArrayList (); List list4 = new ArrayList (); List is a subtype of List  Когда какой wildcard использовать? 15

PECS rule  PECS — P roducer Extends, C onsumer Super   use Foo for a T producer  use Foo for a T consumer  don’t use ? for return type 16

PECS rule  PECS — P roducer Extends, C onsumer Super  use Foo for a T producer  use Foo for a T consumer  don’t use ? for return type  Пример Stack : void pushAll(Collection src); – src is an E producer void popAll(Collection dst); – dst is an E consume 17

PECS rule  Как можно будет использовать объекты внутри метода? void pushAll(Collection src) { dst.add(1); // Не компилируется for (Number n : src) { System.out.println(n); } for (Object o : dst) { System.out.println(o); } void popAll(Collection dst) { dst.add(new Float(1.2)); for (Number n : dst) { // Не компилируется System.out.println(n); } 18

PECS rule  Как можно будет использовать объекты внутри метода? void pushAll(Collection src) { dst.add(1); // Не компилируется for (Number n : src) { System.out.println(n); } void popAll(Collection dst) { dst.add(new Float(1.2)); for (Number n : dst) { // Не компилируется System.out.println(n); } for (Object o : dst) { System.out.println(o); } 19

Wildcards in use  Что можно буедт пердавать в метод? void pushAll(Collection src); void popAll(Collection dst); pushAll(new ArrayList ()); popAll(new ArrayList ()); 20

Wildcards in use  Что можно буедт пердавать в метод? void pushAll(Collection src); void popAll(Collection dst); pushAll(new ArrayList ()); pushAll(new ArrayList ()); // Не компилируется popAll(new ArrayList ()); // Не компилируется popAll(new ArrayList ()); 21

References  