Cours 10 : Type générique
Java depuis la version 1.0. - permet d'écrire du code plus sûr et plus facile à lire qu'un code parsemé de variables Object
Programmation Objet Java–Classes Génériques
Classe générique (Generic class) : une classe dont la définition est paramétrée avec un ou plusieurs types « variables ». class Stack <T> { void push(T o){.
Generics (in Java)
5. Recently : push for simplifying/eliminating wildcards!!! Page 4. 1 A Generic Swap: in different languages template <class T>.
Types paramétrés
Generics de Java. ? Pour : – Le code du generic est vérifié à compile time lors de sa définition. – Le compilateur transforme le code générique en code.
A Generic Type-and-Effect System
24 janv. 2009 Effect systems have recently been used to enforce a locking discipline to prevent race conditions in. Java (Flanagan and Freund 2000; Abadi et ...
Generics in the Java Programming Language
16 févr. 2004 In the introduction we saw invocations of the generic type declaration List
Safe instantiation in Generic Java
The Safe Instantiation Principle: Instantiating a generic class with types that meet the declared constraints on the parameters should not generate any type
Global Type Inference for Featherweight Generic Java
We study global type inference for Featherweight Generic Java (FGJ) a functional Java core language. Given generic class headers and field specifications
Efficient Implementation of Run-time Generic Types for Java
Java which does not support run-time generic types. Our implementation of. NextGen consists of a compiler extending the GJ compiler and a special class.
Efficient Implementation of Run-time Generic Types for Java
Java which does not support run-time generic types. Our implementation of. NextGen consists of a compiler extending the GJ compiler and a special class.
[PDF] Java Generics
You can define your own class as a generic class The class definition code is parameterized by a type typically called This is more or less what
[PDF] Generics in the Java Programming Language - Oracle
5 juil 2004 · A generic type declaration is compiled once and for all and turned into a single class file just like an ordinary class or interface
[PDF] Java Generics
Java generics are realized by mapping parametric genericity to inheritance genericity – The compiler removes all type parameters / arguments
[PDF] Java - Generics - Tutorialspoint
A type parameter also known as a type variable is an identifier that specifies a generic type name The type parameters can be used to declare the return type
[PDF] JAVA GENERICS - Cornell Computer Science
Early versions of Java lacked generics Proposals for adding Generics to Java Java's type system allows the analogous rule for arrays:
[PDF] Generics in Java
Generic types are erased by type erasure in the compiled program ? At runtime there exist only one http://java sun com/j2se/1 5/ pdf /generics-tutorial pdf
[PDF] Generics (in Java)
Java generics simply provide compile-time type safety and eliminate the need for casts Generics use a technique known as type erasure as described above 2013
[PDF] Java et Généricité - FR
One of the new features of Java 1 5 are the Generics They allow us to abstract over types and help us to write type safe code The generics are in some aspects
[PDF] Generics in Java - BVRIT Hyderabad
The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects It makes the code stable by detecting the bugs at compile time Before
[PDF] Java Generics - Department of Computer Sciences
Generics class can be instantiated only with classes (not primitive types) However autoboxing and unboxing of primitive types make generics act as if they
CSC 7322 : Object Oriented Development
J Paul
Gibson, A207
paul.gibson@telecom-sudparis.eu http:// www -public. telecom -sudparis.eu /~gibson/Teaching/CSC7322/2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.1 http:// www -public. telecom -sudparis.eu /~gibson/Teaching/CSC7322/Generics (in Java)
1 Generics - Some HistoryM.D. McIlroy:
Mass-Produced Software Components, Proceedings of the 1st International Conference on Software Engineering, Garmisch Pattenkirchen,Germany, 1968
Joseph A. Goguen
: Parameterized Programming. IEEE Trans. Software Eng.10(5) 1984
David R. Musser, Alexander A. Stepanov
: Generic Programming. ISSAC 19882013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.2Charles W Kreuger
, Software Reuse, ACM Computing Surveys, 1992Ronald Garcia et al
, A Comparative Study of Language Support for GenericProgramming, OOPSLA03, 2003
1 Generics - Some Java HistoryMartin Odersky
andPhilip Wadler
. Pizza into Java: translating theory into practice. In Proceedings of the 24th ACM SIGPLAN-SIGACT symposium on Principles of programming languages (POPL "97).Gilad Bracha, Martin Odersky, David Stoutamire,
andPhilip Wadler
Making the future safe for the past: adding genericity to the Java programming language. SIGPLAN Not.33, 10 (October 1998),May 1999 - Sun proposes to Add Generics to Java, based on GJ. The activity (named JSR 14) is headed by
GiladBracha
Pizza GJ2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.3 activity (named JSR 14) is headed by GiladBracha
JSR-000014 Adding Generics to the JavaTMProgramming Language (Close of Public Review: 01 August 2001) http://jcp.org/aboutJava/communityprocess/review/jsr014/index.htmlMads Torgersen et al ., Adding wildcards to the Java programming language, Proceedings of the 2004 ACM symposium on Applied computing.JSR-000014
JDK1.5
Recently : push for simplifying/eliminating wildcards!!!1 A Generic Swap: in different languages
templateT tmp = a;
a = b; b = tmp; static void Swap2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.4T temp = a;
a = b; b = temp; let swap (a,b) = (b,a)QUESTION: do you
recognise any of these?1 A Generic Swap: in different languages
generic type Swap_Type is private; -- Generic parameter procedure Generic_Swap(Left : in out Swap_Type; Right: in out Swap_Type); procedure Generic_Swap(Left : in out Swap_Type; Right: in out Swap_Type) isTemp : Swap_Type := Left;
beginLeft := Right;
Right := Temp;
end Generic_Swap;2013: J Paul GibsonTSP: Software EngineeringCSC7322/
Generics
.5 class PairT first;
T second;
public staticT temp = p.first;
p.first = p.second; p.second = temp;QUESTION: do you
recognise any of these?1 Why are generics useful
Re-usable patterns (like higher order functions):
foldl (+) 0 [1..5] = 15 foldl (append) "" ["a", "b", "c"] = " abc" filter (odd) [1,3,5,2,4] = [1,3,5]2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.6 filter (odd) [1,3,5,2,4] = [1,3,5] filter (animal) [cow, dog, cake] = [cow, dog] map (double) [1,3,5,2,4] = [2,6,10,4,8] map (capitalize) ["aBc", "BBc"] = ["ABC", "BBC"] QUESTION: what are the types of these 3 functions?1 Why are generics useful
Re-usable data structures, eg binary tree of things:2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.7With generic algorithms/functions, eg depth
1 Why are generics useful
Re-usable classes, eg (ordered) list of
things •Combines generic data and generic functions in a generic class •Unconstrained genericity- no restriction on type/class of generic parameter •Constrained genericity -the generic parameter must be a type/class which isa2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.8 •Constrained genericity -the generic parameter must be a type/class which isasubtype/subclass of a specified classNOTE: Genericity is usually extended to allow multiple generic parameters (but
then they may/may not be mutually constrained)1 Why are generics useful: a classic Java example
List myIntList = new LinkedList();
myIntList.add(new Integer(0));Integer x = (Integer) myIntList.iterator().next(); List
2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.9 myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next(); QUESTION: Which code do you prefer, and why?NOTE : The 2ndexample uses the Java List collections class Why are generics useful: Java List example, continued:public interface List< E> { void add(E x);Iterator iterator();
The declaration of the formal
type parameters of the interface ListYou might
imagine that an IntegerList defined as List2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.10 version of List where E has been uniformly replaced by Integer: public interface IntegerList { void add(Integer x)Iterator iterator();
This intuition may be
useful, but it may also be misleading. (This is closer to the type of macro expansion in theC++ STL)
Java generics implemented by erasure
Generics are implemented by the Java compiler as a front-end conversion called erasure. You can (almost) think of it as a source-to-source translation (syntactic sugar), whereby the generic version of code is converted to the non-generic version. As a result, the type safety and integrity of the Java virtual machine are never at risk, even in the presence of unchecked warnings.2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.11 Basically, erasure gets rid of (or erases) all generic type information. All the type information between angle brackets is thrown out, so, for example, a parameterized type like List2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.12Generics use a technique known as type erasure as described above, and the compiler keeps track of the generics internally, and all instances use the same class file at compile/run time. A C++ template on the other hand is just a fancy macro processor; whenever a template class is instantiated with a new class, the entire
code for the class is reproduced and recompiled for the new class.Some Java "Details" : all instances of a generic class have the same run-time classWhat does the following code fragment print?
List l1 = new ArrayList();
List l2 = new ArrayList();
System.out.println(l1.getClass() == l2.getClass());It prints true , because all instances of a generic class have the same run -time class, 2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.13It prints
true , because all instances of a generic class have the same run -time class, regardless of their actual type parameters. As consequence, the static variables and methods of a class are also shared among all the instances. That is why it is illegal to refer to the type parameters of a type declaration in a static method or initializer, or in the declaration or initializer of a static variable. Generics and SubtypingQUESTION: What does the following code output? class Animal{} class Dog extendsAnimal{ }public classInheritanceTester {
private static void message(CollectionSystem.
out .println( "You gave me a collection of animals."2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.14 private static void message(Object object) {System.
out .println( "You gave me an object." public static void main(String[] args) {List animals =
new ArrayList();
message(animals); Generics and Subtyping
In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.15All OO languages handle the integration of
genericity andsubclassing differentlyThis is probably the hardest thing you need to learn about (Java) generics ... and how it relates to the concept of wildcards
Example: drawing shapes in a canvas
Typically , a drawing will contain a number of shapes. Assuming that the shapes are stored in a list, it would beconvenient to have a method in Canvas that draws them all: public void drawAll(List2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.16 Now, the type rules (as we saw on previous slide) say that drawAll() can only be called on lists of exactly Shape: it cannot, for instance, be called on a Listcould just as well be called on a List
Wildcards - drawing shapes in a canvasWhat we really want is for the method to accept a list of anykind of shape:
public void drawAll(List extends Shape> shapes) { There is a small but very important difference here: wehave replaced the type ListList
extendsShape>.
2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.17List
with List
extendsShape>.
Now drawAll() will accept lists of any subclass of Shape (or Shape itself), so we can now call it on a ListJava WildcardsThere are three types of wildcards in Java:1. "? extends Type": Denotes a family of subtypes of type Type. This is the
most useful wildcard2. "? super Type": Denotes a family of supertypes of type Type.
2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.183. "?": Denotes the set of all types or anyQuestion: can you think of a use of the second wildcard type?
Problem: Implement a Pair Of Thingsin Java
You are to code the class GenericPair, such that it passes the tests written in JUnit_GenericPairTest(which can be downloaded from the module web site).2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.19Problem: Implement a Pair Of Thingsin Java
The test variables
2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.20Problem: Implement a Pair Of Thingsin Java
The tests:
testToString Tests methodGenericPair.toString()testSwap_staticTests methodGenericPair.swap(GenericPair)2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.21testSwapTests methodGenericPair.swap() testCopyConstructorTests methodGenericPair.GenericPair(GenericPair)testEqualsTests methodGenericPair.equals(java.lang.Object)
Problem: Implement a Pair Of Thingsin Java
TO DO: Write the GenericPairso that the tests are successful2013: J Paul GibsonTSP: Software EngineeringCSC7322/
Generics
.22Problem: Implement a Pair Of Thingsin JavaTO DO: Write the GenericPairso that the tests are successful
You should consider the test code to specify the requirements. For example, you can deduce that you need constructors:2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.23Problem: Implement a Pair Of Thingsin Java (
using genericsTO DO: Write the GenericPairso that the tests are successfulFor example, you can also deduce that you need 2 swap methods:
2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.24QUESTION: What other methods do you need?
Problem: Implement a Pair Of Thingsin Java (
without genericsLet us consider how we could do thiswithout
the generic templatesOne such approach is to use the base class Object
public interfacePairSpecification {
Public void
swap(); publicObject
getFirst2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.25 publicObject
getFirst publicObject getSecond();
public void setFirst(Object o); public void setSecond(Object o); publicString toString ();
public boolean equals(Object obj);Problem: Implement a Pair Of Integersin Java (
3 designs
PairSpecification
PairAbstraction
Pair Of Things
2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.26PairOfIntegersAbstraction
PairOfIntegers1
PairOfIntegers2
GenericPair
Integer2
PairOfIntegers3
ArrayList
No generics
Library generics
User defined generics
Pair Of Integers
Problem: Implement a Pair Of Thingsin Javapublic abstract classPairAbstraction
implementsPairSpecification{public abstract
Object getFirst();
public abstractObject getSecond();
2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.27 public abstract void setFirst(Object o); public abstract void setSecond(Object o);Problem: Implement a Pair Of Thingsin Java
publicvoid swap(){Object temp = getFirst();
setFirst(getSecond()); setSecond(temp);2013: J Paul Gibson
TSP: Software EngineeringCSC7322/
Generics
.28 publicString toString (){return
+getFirst()+ +getSecond()+Problem: Implement a Pair Of Thingsin Java
public boolean equals(Object obj){ if (this == obj) return true if (obj == null return false if (!(obj instanceofquotesdbs_dbs20.pdfusesText_26[PDF] generics in java
[PDF] generics in java durgasoft
[PDF] geneva auberge de jeunesse
[PDF] geneva ch
[PDF] geneva college online degree
[PDF] geneva convention 2
[PDF] geneva convention 2020
[PDF] geneva convention 4
[PDF] geneva convention categories
[PDF] geneva convention chemical weapons
[PDF] geneva convention date
[PDF] geneva convention definition
[PDF] geneva convention laws
[PDF] geneva convention pdf