generics lecture

Download Generics lecture

Post on 18-Jul-2015




0 download

Embed Size (px)


  • Generics
  • Create...a box interfaceYou can put into the boxYou can take out of boxNOTE: needs to be able to handle ALL possible types (not just primitives!)GO!

  • Generic Programinggeneric programming is a style of computer programmingwritten in terms of to-be-specified-laterinstantiated when needed for specific types provided as parameters

  • Ex1Given N data structuresGiven M algorithms If we want an algo for every data struct we wind up with NM methodsNOTE: this is BADUsing generics we end up with only N+M methods NODE: this is GOOD

  • Java Generics

  • What are they for?"a type or method to operate on objects of various types while providing compile-time type safety." (Java Programming Language)Basically...IT MAKES LIFE BETTER!!!

  • QUIZ!If my program has 3 types of data structures and 5 types of algorithms...How many methods will there be with NO generics?How many methods will there be WITH generics? GO!

  • The SyntaxObjectName Ex2ArrayList L=new ArrayList();Attention TestCreate a method signature for the put operation for a box, and it takes a generic of some kind


  • Lo Pi HiLets take it up a notch!Ok so there is a catch, if I say Integer, Float, ect. It will not work!!!Why you ask?Attention TestQUIZ!

  • QuizHow do you implement a method with generic type that accepts all subtypes of Number?

  • Now that I have you attentionThe fancy word for this is varianceBut so you can see the big pictureCovariant: converting from a specialized type (Cats) to a more general type (Animals): Every cat is an animal.Contravariant: converting from a general type (Shapes) to a more specialized type (Rectangles): Is this shape a rectangle?Invariant: not able to convert.

  • So how to make this work...Using the Java wild card ?Yes it is the The basic idea is this< ? extends T >< ? super T >Extends means all subtypes of TSuper means all super types of T

  • Ex3

  • See?Any Questions?

    NOTE: there is a lab