SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
CS6202: Advanced Topics in Programming Languages
                                                                           Java 5
                     and Systems
     Lecture 10/11 : Java Generics and Collections                          Some features in new language

             • Overview                                                           boxing/unboxing
             • Subtyping and Wildcard
             • Comparison and Bounds                                              new form of loop
             • Declaration and Erasure
             • Reification and Reflection                                         functions with variable number of arguments
             • Collections
                 • Iterator, Iterable, Collection                                 generics
                 • Set, Queues, List, Maps
             • Design Patterns                                                    more concurrency features
             • Other Issues

CS6202                        Java Generics                 1            CS6202                          Java Generics                               3




 Motiva tion                                                               Java 5 : Example

   Generics is important for:                                                                                        unboxing/boxing
                                                                    generic collection
         software reuse

         type safety
                                                                  new
         optimization (fewer castings)                            loop

   Important Principle :

    “Everything should be as simple as possible but no simpler”                                                             function with variable
                                                                                                                            number of arguments
                                                                                  assert from Java 1.4

CS6202                        Java Generics                 2            CS6202                          Java Generics                               4
Example in Java 1.4                                            Boxing and Unboxing

                                                                  Unboxed types can give better performance

                                                                  Boxed type may be cached for frequent values.



                                                                                                                      60% slower

  similar code with Array in Java 1.4




CS6202                         Java Generics               5   CS6202                     Java Generics                    7




 Generics by Erasure                                             Foreach Loop
                                                                  Works with iterator and is more concise.
   Java Generics is implemented by erasure:                       Kept simple – cannot use remove + multiple lists.
      - simplicity
      - small
      - eases evolution (compatibility)

   List<Integer>, List<String>, List<List<String>>
      erases to just List
                                                                                                 compiles to

   Anomaly : array type very different from parametric type.
         new String[size]
         new ArrayList<String>()
    with the latter losing info on element type.

CS6202                         Java Generics               6   CS6202                     Java Generics                    8
Ite ra tor/ Ite rable Inte rfaces                          Methods with Vara rgs

   Iterator supports iteration through a collection.           Syntactic sugar to support Varargs.           varargs

   Iterable allows an Iterator object to be build.




                                                                The above is compiled to use array.

CS6202                      Java Generics              9    CS6202                      Java Generics                  11




 Methods with Vara rgs
                                                                 Outline
   Arrays can be used to accept a list of elements.
                                                                      • Overview
                                                                      • Subtyping and Wildcard
                                                                      • Comparison and Bounds
                                                                      • Declaration and Erasure
                                                                      • Reification and Reflection
                                                                      • Collections
                                                                          • Iterator, Iterable, Collection
                                                                          • Set, Queues, List, Maps
   Packing argument for array is cumbersome.                          • Design Patterns
                                                                      • Other Issues


CS6202                      Java Generics              10   CS6202                      Java Generics                  12
Subtyping and Substitutions Principle                                Example

   Subtyping Principle :                                                Copy from one list to another :
      A variable of a given type may be assigned a value of any
       subtype of that type. The same applies to arguments.




                                                                        Getting elements :

    However, it is not sound to have:
                 List<Integer> <: List<Number>
    But arrays may be covariant:
                 Integer[] <: Number[]

CS6202                      Java Generics                       13   CS6202                     Java Generics     15




 Cova riant and Contrava riant Subtyping                               Example
   Covariant Subtyping :                                                Putting elements :
         List<Integer> <: List<? extends Number>
   list of elements of any type that is a subtype of Number

   Contravariant Subtyping :
         List<Number> <: List<? super Integer>
   list of elements of any type that is a supertype of Number           Two Bounds? Not legal though plausible.

   Get and Put Principle : use an extends wildcard when you
       only get values out of a structure, use a super wildcard
       when you put values into a structure. Don’t use wildcard
       when you both get and put.

CS6202                      Java Generics                       14   CS6202                     Java Generics     16
Arrays                                                          Wildca rd Capture
     Array subtyping is covariant.                              We can reverse a list using parametric type or wildcard type?

     This was designed before generics.

     Seems irrelevant now :
        - unsound as it relies on runtime checks
        - incompatible with Collection
        - should perhaps deprecate over time.

     One Solution : Use more of Collection rather than Array
        - more flexibility
        - more features/operations
        - better generics
  CS6202                      Java Generics                17    CS6202                      Java Generics                      19




    Wildca rd vs Type Pa rameter                                   Wildca rd Capture
 Wildcards may be used if only Objects are being read.          Solution is to use a wrapper function with wildcard capture :
Collection<?> also stands for Collection<? extends Object>




Alternative (more restrictive but safer).
                                                                This solution is similar to a open/close capture of an
                                                                existential type.


  CS6202                      Java Generics                18    CS6202                      Java Generics                      20
Re striction on Wildca rds
Wildcards should not appear at                                        Outline
   (i) top-level of class instance creation
   (ii) explicit type parameters of generic method                        • Overview
   (iii) in supertypes of extends/implements                              • Subtyping and Wildcard
                                                                          • Comparison and Bounds
                                                                          • Declaration and Erasure
                                                                          • Reification and Reflection
                                                                          • Collections
                                                                              • Iterator, Iterable, Collection
                                                                              • Set, Queues, List, Maps
                                                                          • Design Patterns
                                                                          • Other Issues


 CS6202                     Java Generics                   21   CS6202                     Java Generics               23




   Re striction on Wildca rds                                     Compa rison and Bounds
Restriction on supertype of extends/implements                     x.compareTo(y) method is based on natural ordering
                                                                      x less_than y returns a negative value
                                                                      x equal_to y returns zero
                                                                      x more_than y returns a positive value




Restriction on explicit parameter of methods
                                                                    Consistency with equal
                                                                       x.equals(y) if and only if x.compareTo(y)==0

                                                                    Main difference with null
                                                                       x.equals(null) returns false
                                                     permitted         x.compareTo(null) throws an exception
 CS6202                     Java Generics                   22   CS6202                     Java Generics               24
Contract for Compa rable                                 Maximum of a Collection
                                                         Generic code to find maximum :          need to compare
Anti-symmetric :
                                                                                                 with its own type
    sgn(x.compareTo(y)) == -sgn(y.compareTo(x))

Transitivity :
   if x.compareTo(y)<0 and y.compareTo(z)<0
   then x.compareTo(z)<0

Congruence :
 if x.compareTo(y)==0 then                               A more general signature is based on get/put principle:
    forall z. sgn(x.compareTo(z)==sgn(x.compareTo(z))



 CS6202                   Java Generics             25    CS6202                     Java Generics                               27




   Implementing Integer a s Compa rable                     Fruity Example
Correct way :                                            There is some control over what can be compared.




                                                                                              cannot compare apple with orange
Incorrect way - overflow problem :




                                                                                           can now compare between orange/apple



 CS6202                   Java Generics             26    CS6202                     Java Generics                               28
Fruity Example                                             Compa rator
Recall :                                                    Implement max using Comparator :




This works for List<Orange> and List<Fruit>, but old
version works for only List<Fruit> .
                                                            Comparator from natural order :




 CS6202                     Java Generics              29    CS6202                     Java Generics                       31




  Compa rator                                                  Enumerated Type s
Allows additional ad-hoc ordering to be specified :         Enumerated type corresponds to a class with a set of final static
                                                            values. First, an abstract class :



Example : shorter string is smaller


                                                                                                             compare within same
                                                                                                             enumerated type only




 CS6202                     Java Generics              30    CS6202                     Java Generics                       32
Enumerated Type
An instance of enumerated type.
                                                                        Outline
                                                                             • Overview
                                                                             • Subtyping and Wildcard
                                                                             • Comparison and Bounds
                                                                             • Declaration and Erasure
                                                                             • Reification and Reflection
                                                                             • Collections
                                                                                 • Iterator, Iterable, Collection
                                                                                 • Set, Queues, List, Maps
                                                                             • Design Patterns
                                                                             • Other Issues


 CS6202                     Java Generics                    33    CS6202                      Java Generics                  35




  Cova riant Overriding                                             Constructors
Java 5 can override another if arguments match exactly but the    Actual type parameters should be provided :
result of overriding method is a subtype of other method.
                                                                  Pair<String,Integer> p = new
Useful for clone method :                                                    Pair<String,Integer>(“one”,2)
 class Object {
          :
     public Object clone() { … }
                                                                   If you forget, it is a raw type with unchecked warning :
   }

  class Point {                                                    Pair<String,Integer> p = new Pair(“one”,2)
         :
     public Point clone() { return new Point(x,y);}
  }
                        covariant overriding

 CS6202                     Java Generics                    34    CS6202                      Java Generics                  36
Sta tic Members
Static methods are independent of any type parameters :
                                                                     Outline
                                                                          • Overview
Cell.getCount()                  // ok                                    • Subtyping and Wildcard
                                                                          • Comparison and Bounds
Cell<Integer>.getCount() // compile-time error                            • Declaration and Erasure
Cell<?>.getCount()              // compile-time error
                                                                          • Reification and Reflection
                                                                          • Collections
                                                                              • Iterator, Iterable, Collection
                                                                              • Set, Queues, List, Maps
                                                                          • Design Patterns
                                                                          • Other Issues


 CS6202                    Java Generics                  37    CS6202                      Java Generics                   39




   How Erasure Works                                              Reification
                                                               Refers to an ability to get run-time type information.
                                                               This is a kind of concretization.

                                                               Array is reified with its component type, but
                                                               parameterized types is reified without its component type.


                                                                Number[]      has reified type Number[]

                                                                ArrayList<Number> has reified type ArrayList




 CS6202                    Java Generics                  38    CS6202                      Java Generics                   40
Reified Type s                                                Reification - Arrays
Type that is reifiable.                                       More problem :




 Type that is not reifiable.




 CS6202                        Java Generics             41    CS6202              Java Generics   43




   Reification                                                   Reification - Arrays
An incorrect code to convert a collection to an array.        More problem :




                           not reifiable




 CS6202                        Java Generics             42    CS6202              Java Generics   44
Reification - Arrays                                 Re flection
Alternative using another array + reflection!        Reflection is a term to allow a program to examine its own
                                                     definition.

                                                     Generics for reflection supports the process using new generic
                                                     programming techniques.

                                                     Reflection for generics allow generic types (e.g. type vars,
                                                     wildcard types) to be captured at runtime.




 CS6202                     Java Generics       45    CS6202                      Java Generics                       47




   Reification - Arrays                                 Generics for Re flection
Solution using a Class – runtime type!
                                                     A new generic type for Class




 CS6202                     Java Generics       46    CS6202                      Java Generics                       48
Re flection for Primitive Type                                Re flection for Gene ric
                                                                 Non-generic reflection example :
 We cannot use Class<int> as type parameter must be reference
 type. Use Class<Integer> for int.class instead!


Java.lang.reflect.array.newInstances(int.class,size)
  returns int[] and not Integer[] through a hack!


However, int[].class is correctly denoted by Class<int[]>         Output :




  CS6202                   Java Generics                    49   CS6202                           Java Generics         51




   Generic Re flection Libra ry                                   Re flection for Gene ric
                                                                 Generic reflection example :




                       newArray




                                                                  Output :
                       newArray




                                                                          Bytecode contains generic type information!
  CS6202                   Java Generics                    50   CS6202                           Java Generics         52
Re flecting Generic Type s
Type interface to describe generic type :




CS6202                      Java Generics   53

Mais conteúdo relacionado

Mais procurados

5장. Execution Engine
5장. Execution Engine5장. Execution Engine
5장. Execution Engine김 한도
 
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture3
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture3Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture3
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture3AL-AWAIL for Electronic Engineering
 
Xml Syntax Quick Reference
Xml Syntax Quick ReferenceXml Syntax Quick Reference
Xml Syntax Quick ReferenceLiquidHub
 
Xm Lquickref
Xm LquickrefXm Lquickref
Xm LquickrefLiquidHub
 
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)Dan Allen
 
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture4
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture4Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture4
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture4AL-AWAIL for Electronic Engineering
 
Java Reference
Java ReferenceJava Reference
Java Referencekhoj4u
 
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...Dan Allen
 
2장. Runtime Data Areas
2장. Runtime Data Areas2장. Runtime Data Areas
2장. Runtime Data Areas김 한도
 
C the complete_reference
C the complete_referenceC the complete_reference
C the complete_referencevinukondakiran
 
The Anatomy of Analysis Tools (EVO 2008)
The Anatomy of Analysis Tools (EVO 2008)The Anatomy of Analysis Tools (EVO 2008)
The Anatomy of Analysis Tools (EVO 2008)Tudor Girba
 
6장 Thread Synchronization
6장 Thread Synchronization6장 Thread Synchronization
6장 Thread Synchronization김 한도
 
O hst-05 design-of_the_occupant_protection_system_mahindra
O hst-05 design-of_the_occupant_protection_system_mahindraO hst-05 design-of_the_occupant_protection_system_mahindra
O hst-05 design-of_the_occupant_protection_system_mahindraAnand Kumar Chinni
 
Java Programming Guide Quick Reference
Java Programming Guide Quick ReferenceJava Programming Guide Quick Reference
Java Programming Guide Quick ReferenceFrescatiStory
 

Mais procurados (19)

C++ material
C++ materialC++ material
C++ material
 
5장. Execution Engine
5장. Execution Engine5장. Execution Engine
5장. Execution Engine
 
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture3
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture3Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture3
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture3
 
Xml Syntax Quick Reference
Xml Syntax Quick ReferenceXml Syntax Quick Reference
Xml Syntax Quick Reference
 
Xm Lquickref
Xm LquickrefXm Lquickref
Xm Lquickref
 
groovy
groovygroovy
groovy
 
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)
JSR-299 (CDI), Weld & the Future of Seam (JavaOne 2010)
 
Jstl 8
Jstl 8Jstl 8
Jstl 8
 
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture4
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture4Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture4
Embedded System Microcontroller Interactive Course using BASCOM-AVR - Lecture4
 
Java J2EE Training in Chennai, Tambaram
Java J2EE  Training in Chennai, TambaramJava J2EE  Training in Chennai, Tambaram
Java J2EE Training in Chennai, Tambaram
 
Java Reference
Java ReferenceJava Reference
Java Reference
 
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
Throwing complexity over the wall: Rapid development for enterprise Java (Jav...
 
0 E158 C10d01
0 E158 C10d010 E158 C10d01
0 E158 C10d01
 
2장. Runtime Data Areas
2장. Runtime Data Areas2장. Runtime Data Areas
2장. Runtime Data Areas
 
C the complete_reference
C the complete_referenceC the complete_reference
C the complete_reference
 
The Anatomy of Analysis Tools (EVO 2008)
The Anatomy of Analysis Tools (EVO 2008)The Anatomy of Analysis Tools (EVO 2008)
The Anatomy of Analysis Tools (EVO 2008)
 
6장 Thread Synchronization
6장 Thread Synchronization6장 Thread Synchronization
6장 Thread Synchronization
 
O hst-05 design-of_the_occupant_protection_system_mahindra
O hst-05 design-of_the_occupant_protection_system_mahindraO hst-05 design-of_the_occupant_protection_system_mahindra
O hst-05 design-of_the_occupant_protection_system_mahindra
 
Java Programming Guide Quick Reference
Java Programming Guide Quick ReferenceJava Programming Guide Quick Reference
Java Programming Guide Quick Reference
 

Destaque (20)

Applying Generics
Applying GenericsApplying Generics
Applying Generics
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Data structure circular list
Data structure circular listData structure circular list
Data structure circular list
 
Data structures1
Data structures1Data structures1
Data structures1
 
It6601 mobile computing unit 4 questions
It6601 mobile computing unit 4 questionsIt6601 mobile computing unit 4 questions
It6601 mobile computing unit 4 questions
 
Stack in Sata Structure
Stack in Sata StructureStack in Sata Structure
Stack in Sata Structure
 
IT6601 Mobile Computing
IT6601 Mobile  Computing IT6601 Mobile  Computing
IT6601 Mobile Computing
 
Double linked list
Double linked listDouble linked list
Double linked list
 
Data Structure (Circular Linked List)
Data Structure (Circular Linked List)Data Structure (Circular Linked List)
Data Structure (Circular Linked List)
 
IT6601 MOBILE COMPUTING UNIT1
IT6601 MOBILE COMPUTING UNIT1IT6601 MOBILE COMPUTING UNIT1
IT6601 MOBILE COMPUTING UNIT1
 
IT6601 MOBILE COMPUTING
IT6601 MOBILE COMPUTINGIT6601 MOBILE COMPUTING
IT6601 MOBILE COMPUTING
 
It6601 mobile computing unit 5
It6601 mobile computing unit 5It6601 mobile computing unit 5
It6601 mobile computing unit 5
 
It6601 mobile computing unit 3
It6601 mobile computing unit 3It6601 mobile computing unit 3
It6601 mobile computing unit 3
 
IT6601 MOBILE COMPUTING
IT6601 MOBILE COMPUTINGIT6601 MOBILE COMPUTING
IT6601 MOBILE COMPUTING
 
IT6601 MOBILE COMPUTING
IT6601 MOBILE COMPUTINGIT6601 MOBILE COMPUTING
IT6601 MOBILE COMPUTING
 
It6601 mobile computing unit 4
It6601 mobile computing unit 4It6601 mobile computing unit 4
It6601 mobile computing unit 4
 
It6601 mobile computing unit2
It6601 mobile computing unit2It6601 mobile computing unit2
It6601 mobile computing unit2
 
Linked list
Linked listLinked list
Linked list
 
IT6601 MOBILE COMPUTING
IT6601 MOBILE COMPUTINGIT6601 MOBILE COMPUTING
IT6601 MOBILE COMPUTING
 
DSA-2012-Lect00
DSA-2012-Lect00DSA-2012-Lect00
DSA-2012-Lect00
 

Semelhante a 10 generics a-4_in_1

Scala: An experience report
Scala: An experience reportScala: An experience report
Scala: An experience reportMark Needham
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin ProgrammingAtlassian
 
Protecting Source Code
Protecting Source CodeProtecting Source Code
Protecting Source CodeGodfrey Nolan
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & RailsPeter Lind
 
Adapter 2pp
Adapter 2ppAdapter 2pp
Adapter 2pprajjani
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Getting ready to java 8
Getting ready to java 8Getting ready to java 8
Getting ready to java 8DataArt
 
Getting ready to java 8
Getting ready to java 8Getting ready to java 8
Getting ready to java 8Strannik_2013
 
Cascalog at Strange Loop
Cascalog at Strange LoopCascalog at Strange Loop
Cascalog at Strange Loopnathanmarz
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1PawanMM
 
What's new in Java 8
What's new in Java 8What's new in Java 8
What's new in Java 8jclingan
 
The latest features coming to Java 12
The latest features coming to Java 12The latest features coming to Java 12
The latest features coming to Java 12NexSoftsys
 
JRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMJRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMRaimonds Simanovskis
 
Tutorial visitor
Tutorial visitorTutorial visitor
Tutorial visitorWei Wang
 
Section 6 collections generics
Section 6   collections genericsSection 6   collections generics
Section 6 collections genericsJuarez Junior
 

Semelhante a 10 generics a-4_in_1 (20)

Scala: An experience report
Scala: An experience reportScala: An experience report
Scala: An experience report
 
Polyglot Plugin Programming
Polyglot Plugin ProgrammingPolyglot Plugin Programming
Polyglot Plugin Programming
 
Protecting Source Code
Protecting Source CodeProtecting Source Code
Protecting Source Code
 
Java, Ruby & Rails
Java, Ruby & RailsJava, Ruby & Rails
Java, Ruby & Rails
 
Adapter 2pp
Adapter 2ppAdapter 2pp
Adapter 2pp
 
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Getting ready to java 8
Getting ready to java 8Getting ready to java 8
Getting ready to java 8
 
Learning java
Learning javaLearning java
Learning java
 
Getting ready to java 8
Getting ready to java 8Getting ready to java 8
Getting ready to java 8
 
Cascalog at Strange Loop
Cascalog at Strange LoopCascalog at Strange Loop
Cascalog at Strange Loop
 
Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1Session 38 - Core Java (New Features) - Part 1
Session 38 - Core Java (New Features) - Part 1
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
 
Java 8
Java 8Java 8
Java 8
 
What's new in Java 8
What's new in Java 8What's new in Java 8
What's new in Java 8
 
The latest features coming to Java 12
The latest features coming to Java 12The latest features coming to Java 12
The latest features coming to Java 12
 
Lambdas in Java 8
Lambdas in Java 8Lambdas in Java 8
Lambdas in Java 8
 
JRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVMJRuby - Programmer's Best Friend on JVM
JRuby - Programmer's Best Friend on JVM
 
Core java
Core javaCore java
Core java
 
Tutorial visitor
Tutorial visitorTutorial visitor
Tutorial visitor
 
Section 6 collections generics
Section 6   collections genericsSection 6   collections generics
Section 6 collections generics
 

Último

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Último (20)

Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

10 generics a-4_in_1

  • 1. CS6202: Advanced Topics in Programming Languages Java 5 and Systems Lecture 10/11 : Java Generics and Collections Some features in new language • Overview boxing/unboxing • Subtyping and Wildcard • Comparison and Bounds new form of loop • Declaration and Erasure • Reification and Reflection functions with variable number of arguments • Collections • Iterator, Iterable, Collection generics • Set, Queues, List, Maps • Design Patterns more concurrency features • Other Issues CS6202 Java Generics 1 CS6202 Java Generics 3 Motiva tion Java 5 : Example Generics is important for: unboxing/boxing generic collection software reuse type safety new optimization (fewer castings) loop Important Principle : “Everything should be as simple as possible but no simpler” function with variable number of arguments assert from Java 1.4 CS6202 Java Generics 2 CS6202 Java Generics 4
  • 2. Example in Java 1.4 Boxing and Unboxing Unboxed types can give better performance Boxed type may be cached for frequent values. 60% slower similar code with Array in Java 1.4 CS6202 Java Generics 5 CS6202 Java Generics 7 Generics by Erasure Foreach Loop Works with iterator and is more concise. Java Generics is implemented by erasure: Kept simple – cannot use remove + multiple lists. - simplicity - small - eases evolution (compatibility) List<Integer>, List<String>, List<List<String>> erases to just List compiles to Anomaly : array type very different from parametric type. new String[size] new ArrayList<String>() with the latter losing info on element type. CS6202 Java Generics 6 CS6202 Java Generics 8
  • 3. Ite ra tor/ Ite rable Inte rfaces Methods with Vara rgs Iterator supports iteration through a collection. Syntactic sugar to support Varargs. varargs Iterable allows an Iterator object to be build. The above is compiled to use array. CS6202 Java Generics 9 CS6202 Java Generics 11 Methods with Vara rgs Outline Arrays can be used to accept a list of elements. • Overview • Subtyping and Wildcard • Comparison and Bounds • Declaration and Erasure • Reification and Reflection • Collections • Iterator, Iterable, Collection • Set, Queues, List, Maps Packing argument for array is cumbersome. • Design Patterns • Other Issues CS6202 Java Generics 10 CS6202 Java Generics 12
  • 4. Subtyping and Substitutions Principle Example Subtyping Principle : Copy from one list to another : A variable of a given type may be assigned a value of any subtype of that type. The same applies to arguments. Getting elements : However, it is not sound to have: List<Integer> <: List<Number> But arrays may be covariant: Integer[] <: Number[] CS6202 Java Generics 13 CS6202 Java Generics 15 Cova riant and Contrava riant Subtyping Example Covariant Subtyping : Putting elements : List<Integer> <: List<? extends Number> list of elements of any type that is a subtype of Number Contravariant Subtyping : List<Number> <: List<? super Integer> list of elements of any type that is a supertype of Number Two Bounds? Not legal though plausible. Get and Put Principle : use an extends wildcard when you only get values out of a structure, use a super wildcard when you put values into a structure. Don’t use wildcard when you both get and put. CS6202 Java Generics 14 CS6202 Java Generics 16
  • 5. Arrays Wildca rd Capture Array subtyping is covariant. We can reverse a list using parametric type or wildcard type? This was designed before generics. Seems irrelevant now : - unsound as it relies on runtime checks - incompatible with Collection - should perhaps deprecate over time. One Solution : Use more of Collection rather than Array - more flexibility - more features/operations - better generics CS6202 Java Generics 17 CS6202 Java Generics 19 Wildca rd vs Type Pa rameter Wildca rd Capture Wildcards may be used if only Objects are being read. Solution is to use a wrapper function with wildcard capture : Collection<?> also stands for Collection<? extends Object> Alternative (more restrictive but safer). This solution is similar to a open/close capture of an existential type. CS6202 Java Generics 18 CS6202 Java Generics 20
  • 6. Re striction on Wildca rds Wildcards should not appear at Outline (i) top-level of class instance creation (ii) explicit type parameters of generic method • Overview (iii) in supertypes of extends/implements • Subtyping and Wildcard • Comparison and Bounds • Declaration and Erasure • Reification and Reflection • Collections • Iterator, Iterable, Collection • Set, Queues, List, Maps • Design Patterns • Other Issues CS6202 Java Generics 21 CS6202 Java Generics 23 Re striction on Wildca rds Compa rison and Bounds Restriction on supertype of extends/implements x.compareTo(y) method is based on natural ordering x less_than y returns a negative value x equal_to y returns zero x more_than y returns a positive value Restriction on explicit parameter of methods Consistency with equal x.equals(y) if and only if x.compareTo(y)==0 Main difference with null x.equals(null) returns false permitted x.compareTo(null) throws an exception CS6202 Java Generics 22 CS6202 Java Generics 24
  • 7. Contract for Compa rable Maximum of a Collection Generic code to find maximum : need to compare Anti-symmetric : with its own type sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) Transitivity : if x.compareTo(y)<0 and y.compareTo(z)<0 then x.compareTo(z)<0 Congruence : if x.compareTo(y)==0 then A more general signature is based on get/put principle: forall z. sgn(x.compareTo(z)==sgn(x.compareTo(z)) CS6202 Java Generics 25 CS6202 Java Generics 27 Implementing Integer a s Compa rable Fruity Example Correct way : There is some control over what can be compared. cannot compare apple with orange Incorrect way - overflow problem : can now compare between orange/apple CS6202 Java Generics 26 CS6202 Java Generics 28
  • 8. Fruity Example Compa rator Recall : Implement max using Comparator : This works for List<Orange> and List<Fruit>, but old version works for only List<Fruit> . Comparator from natural order : CS6202 Java Generics 29 CS6202 Java Generics 31 Compa rator Enumerated Type s Allows additional ad-hoc ordering to be specified : Enumerated type corresponds to a class with a set of final static values. First, an abstract class : Example : shorter string is smaller compare within same enumerated type only CS6202 Java Generics 30 CS6202 Java Generics 32
  • 9. Enumerated Type An instance of enumerated type. Outline • Overview • Subtyping and Wildcard • Comparison and Bounds • Declaration and Erasure • Reification and Reflection • Collections • Iterator, Iterable, Collection • Set, Queues, List, Maps • Design Patterns • Other Issues CS6202 Java Generics 33 CS6202 Java Generics 35 Cova riant Overriding Constructors Java 5 can override another if arguments match exactly but the Actual type parameters should be provided : result of overriding method is a subtype of other method. Pair<String,Integer> p = new Useful for clone method : Pair<String,Integer>(“one”,2) class Object { : public Object clone() { … } If you forget, it is a raw type with unchecked warning : } class Point { Pair<String,Integer> p = new Pair(“one”,2) : public Point clone() { return new Point(x,y);} } covariant overriding CS6202 Java Generics 34 CS6202 Java Generics 36
  • 10. Sta tic Members Static methods are independent of any type parameters : Outline • Overview Cell.getCount() // ok • Subtyping and Wildcard • Comparison and Bounds Cell<Integer>.getCount() // compile-time error • Declaration and Erasure Cell<?>.getCount() // compile-time error • Reification and Reflection • Collections • Iterator, Iterable, Collection • Set, Queues, List, Maps • Design Patterns • Other Issues CS6202 Java Generics 37 CS6202 Java Generics 39 How Erasure Works Reification Refers to an ability to get run-time type information. This is a kind of concretization. Array is reified with its component type, but parameterized types is reified without its component type. Number[] has reified type Number[] ArrayList<Number> has reified type ArrayList CS6202 Java Generics 38 CS6202 Java Generics 40
  • 11. Reified Type s Reification - Arrays Type that is reifiable. More problem : Type that is not reifiable. CS6202 Java Generics 41 CS6202 Java Generics 43 Reification Reification - Arrays An incorrect code to convert a collection to an array. More problem : not reifiable CS6202 Java Generics 42 CS6202 Java Generics 44
  • 12. Reification - Arrays Re flection Alternative using another array + reflection! Reflection is a term to allow a program to examine its own definition. Generics for reflection supports the process using new generic programming techniques. Reflection for generics allow generic types (e.g. type vars, wildcard types) to be captured at runtime. CS6202 Java Generics 45 CS6202 Java Generics 47 Reification - Arrays Generics for Re flection Solution using a Class – runtime type! A new generic type for Class CS6202 Java Generics 46 CS6202 Java Generics 48
  • 13. Re flection for Primitive Type Re flection for Gene ric Non-generic reflection example : We cannot use Class<int> as type parameter must be reference type. Use Class<Integer> for int.class instead! Java.lang.reflect.array.newInstances(int.class,size) returns int[] and not Integer[] through a hack! However, int[].class is correctly denoted by Class<int[]> Output : CS6202 Java Generics 49 CS6202 Java Generics 51 Generic Re flection Libra ry Re flection for Gene ric Generic reflection example : newArray Output : newArray Bytecode contains generic type information! CS6202 Java Generics 50 CS6202 Java Generics 52
  • 14. Re flecting Generic Type s Type interface to describe generic type : CS6202 Java Generics 53