SlideShare a Scribd company logo
Java course - IAG0040




             Enums, Generics
               & Assertions



Anton Keks                           2011
Arrays helper class
 ●
     Arrays class provides operations on arrays
     –   asList() - provides a view of an array as a List
     –   binarySearch() - searches for an element from a sorted
         array
     –   equals() - checks two arrays for equality
     –   fill() - fills an array with the specified element
     –   sort() - sorts an array (using a tuned QuickSort algorithm)
     –   toString() - can be used for displaying of arrays
     –   deepToString() - the same for multidimensional arrays


Java course – IAG0040                                         Lecture 5
Anton Keks                                                      Slide 2
Collections helper class
 ●
     Provides constants and operations on Collections
      –   EMPTY_XXX or emptyXXX() - immutable empty collection
      –   sort(), binarySearch(), fill(), copy(), min(), max(),
          shuffle(), replaceAll(), rotate(), swap()
      –   singletonXXX() - immutable collection with one element
      –   enumeration() - for support of legacy classes
 ●   Wrappers
      –   checkedXXX() - a dynamically typesafe view
      –   unmodifiableXXX() - an unmodifiable view
      –   synchronizedXXX() - a synchronized view


Java course – IAG0040                                            Lecture 5
Anton Keks                                                         Slide 3
Tips
 ●   Program to interfaces
      –   List list = new ArrayList();
 ●   Copy (or conversion) constructors
      –   Set set = new TreeSet(map.values());
 ●   Checking if the Collection is empty
      –   collection.isEmpty()
      –   collection.size() == 0 may be very expensive
 ●   Remove all nulls (or other elements):
      –   collection.removeAll(Collections.singleton(null))
 ●   Convert to arrays
      –   String[] s = c.toArray(new String[c.size()]);
Java course – IAG0040                                    Lecture 5
Anton Keks                                                 Slide 4
Tips (cont)
 ●   Iterate Maps with Map.Entry if you need both keys and values
      –   for(Map.Entry e : map.entrySet()) {}
 ●   Initial capacity in case of HashSet, HashMap, and ArrayList
      –   new ArrayList(512)
 ●
     Operations on sublists are reflected in the main lists
      –   list.subList(15, 16).remove(object);
 ●   All collections implement toString()
      –   useful for displaying the contents quickly




Java course – IAG0040                                               Lecture 5
Anton Keks                                                            Slide 5
Inner classes
 ●   Inner classes can be defined inside of other classes
     –   class MyClass {
           class InnerClass { }
         }
     –   non static inner classes can access internals of parent
         classes
     –   static inner classes cannot




Java course – IAG0040                                       Lecture 5
Anton Keks                                                    Slide 6
Anonymous inner classes
 ●
     Classes can be created and instantiated 'inline'
      –   Runnable runnable = new Runnable() {
             public void run() {
                System.out.println("Running!");
             }
          };
          runnable.run();
 ●
     Analogous to initialization of arrays: new byte[] {1}
 ●   Very useful for implementation of short interfaces, where the
     code is needed as part of the surrounding code
 ●   Compiled into ParentClass$1.class, where $1 is the index of the
     anonymous class within the ParentClass

Java course – IAG0040                                         Lecture 5
Anton Keks                                                      Slide 7
Annotations
 ●
     Annotations are special type of interfaces
     –   @interface MyAnnotation { }
     –   Allow specification of meta data for source code elements
          ●   Used before the element in question, just like Javadoc
     –   In general, don't have effect at runtime
     –   Built-in: @SupressWarnings, @Deprecated,
                   @Override, @Generated, etc
     –   Can take parameters: @SupressWarnings(“unused”)
         or @SupressWarnings(value=“unused”)
 ●   Very useful in various frameworks, e.g. JUnit4, Spring2,
     Hibernate3, EJB3
Java course – IAG0040                                          Lecture 5
Anton Keks                                                       Slide 8
Enums
 ●   Special type of class (base class is java.lang.Enum)
 ●   enum Season {WINTER, SPRING, SUMMER, AUTUMN}
 ●   Only one instance of each constant is guaranteed; enums cannot be
     instantiated; they are implicitly final (cannot be extended)
 ●   Constructors can be used: WINTER(1), SPRING(“Hello”)
 ●   Accessed like constants: Season.WINTER
 ●   Every enum has the following methods:
      –   int ordinal() - returns an ordinal value of the constant
      –   String name() - returns the name of the constant
      –   static Enum valueOf(String name) - returns the enum constant
      –   static Season[] values() - returns an array of all constants
 ●   See Season and Planet in net.azib.java.lessons.enums
Java course – IAG0040                                                    Lecture 5
Anton Keks                                                                 Slide 9
Introduction to Generics
 ●   Are there any problems with collections?
      –   String s = (String) list.get(3);
 ●
     Java 1.5 introduced generics for type safety checks
      –   List<String> list;
          String s = list.get(3);
 ●   Additionally, generics allow to abstract over types
      –   List<Integer> list = Arrays.asList(
                               new Integer[]{1,2});
      –   List<String> list = Arrays.asList(
                              “a”, “b”, “c”);
 ●   Provide more compile time information for error checking
Java course – IAG0040                                      Lecture 5
Anton Keks                                                  Slide 10
Defining generic classes
 ●   public interface List<E> {
        void add(E x);
        Iterator<E> iterator();
     }
 ●   public interface Iterator<E>{
        E next();
        boolean hasNext();
     }
 ●   Formal type parameters are in the angle brackets <>
 ●
     In invocations of generic types (parametrized types), all occurrences
     of formal types are replaced by the actual argument
 ●
     Primitives cannot be used as arguments, but arrays and wrappers can
      –   Iterator<int[]> i;       List<Integer> intList;

Java course – IAG0040                                             Lecture 5
Anton Keks                                                         Slide 11
Defining generics
 ●
     Generics can be thought of as if they were expanded
     –   public interface ListOfIntegers {
           void add(Integer x);
           Iterator<Integer> iterator();
         }
 ●   Actually they are not: generics introduce no memory or
     performance overhead
 ●   Information about type parameters is stored in class files
     and used during compilation
 ●   Use possibly meaningful single character names
     –   E = Element, T = Type, K = Key, V = Value, etc
Java course – IAG0040                                     Lecture 5
Anton Keks                                                 Slide 12
Generics usage in Java API
 ●
     Collection<E>, Iterable<E>, Iterator<E>
 ●
     Set<E>, List<E>, Queue<E>
      –   Set<String> set = new HashSet<String>();
      –   Queue<Dog> q = new LinkedList<Dog>();
 ●   Map<K, V>
      –   Map<String, Thread> map =
          new HashMap<String, Thread>();
 ●
     Comparator<T>, Comparable<T>
 ●
     Class<T>
      –   Date d = Date.class.newInstance();

Java course – IAG0040                             Lecture 5
Anton Keks                                         Slide 13
Subtyping
 ●   If A extends B, does List<A> extend List<B>?
 ●   List<String> ls = new ArrayList<String>();
     List<Object> lo = ls;
     –   this is illegal – List of Strings is not a List of Objects
 ●   lo.add(new Integer(42)); // adds an illegal object
     String s = ls.get(0);    // this is not a String!
     –   this code would break type safety at runtime!
 ●   However
     –   ls instanceof List & lo instanceof List
     –   Collection<String> cs = ls;                     // legal


Java course – IAG0040                                                 Lecture 5
Anton Keks                                                             Slide 14
Backward compatibility
 ●
     Generics are backward compatible
      –   Java 1.5 still had to be able to run old (unparameterized) code
      –   Backward compatibility has influenced the implementation
 ●   Old-style (unparameterized or raw-type) code can still be written
      –   ArrayList al = new ArrayList<String>();
          ArrayList<String> al = new ArrayList();
 ●   For now, checks are only done at compile time
      –   At runtime, generic collections hold Objects ('type erasure')
      –   Collections.checkedXXX() methods may be used for runtime
          type checking
      –   Implementation may change in future

Java course – IAG0040                                                Lecture 5
Anton Keks                                                            Slide 15
Wildcards
 ●   void printCollection(Collection<Object> c) {
        for (Object e : c)
           System.out.println(e);
     }
 ●   printCollection(new ArrayList<String>()) //           doesn't compile

 ●   void printCollection(Collection<?> c) { // ? is a wildcard
        for (Object e : c)
           System.out.println(e);
     }
 ●   However the following fails (at compile time!)
      –   c.add(new Object());
      –   Collection<?> means “collection of unknown”, it is read-only
      –   Unknown <?> can always be assigned to Object (when reading)

Java course – IAG0040                                          Lecture 5
Anton Keks                                                      Slide 16
Bounded wildcards
 ●
     <? extends T> means “anything that extends T”
     –   upper bounded wildcard, “read-only”
     –   List<? extends Number> vs List<Number>
     –   List<Integer> can be assigned to the first one, but not to the
         second one
     –   add() still doesn't work, because actual type is not known
 ●
     <? super T> means “anything that is a supertype of T”
     –   lower bounded wildcard, “write-only”
     –   List<? super Number> vs List<Number>
     –   add(new Integer(5)) works, because Integer can be
         assigned to any supertype of Number or Number itself

Java course – IAG0040                                             Lecture 5
Anton Keks                                                         Slide 17
Generic methods
 ●
     Methods can also be generic, independently from their classes
 ●   Generic methods can substitute wildcard types
      –   boolean containsAll(Collection<?> c);
          <T> boolean containsAll(Collection<T> c);
 ●
     But it is more reasonable to use in case a type is used many times
      –   <T> void copy(List<T> dest, List<? extends T> src);
          <T, S extends T> void copy(
                                 List<T> dest, List<S> src);
 ●   T is selected automatically based on the passed types (it is always
     the most specific type possible), its usage is implicit
 ●   Relative type dependencies are important (extends / super)


Java course – IAG0040                                             Lecture 5
Anton Keks                                                         Slide 18
Generics tasks
 ●
     Use generics in
     WordFrequencyCalculatorImpl and
     DuplicateRemoverImpl
 ●   Write some new classes
     –   Circle and Square
          ●   both should extend the provided
              net.azib.java.lessons.collections.Shape
     –   ShapeAggregatorImpl (which should implement
         the ShapeAggregator)


Java course – IAG0040                              Lecture 5
Anton Keks                                          Slide 19
Assertions
 ●
     assert keyword can be used for assertion of validity of
     boolean expressions (a debugging feature)
      –   assert boolean-expression : value-expression;
      –   assert A == 5 : “A is not 5!!!”;
 ●
     If boolean-expression evaluates to false, an AssertionError is
     thrown with the value-expression as detailed message (optional)
 ●
     Assertions are disabled by default, therefore have no runtime
     overhead
 ●
     When enabled, help to write self-documented code and trace
     bugs at runtime
 ●
     java -ea switch enables assertions (specific packages and classes
     may be specified if global activation is not desired)
Java course – IAG0040                                          Lecture 5
Anton Keks                                                      Slide 20

More Related Content

What's hot

Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Singsys Pte Ltd
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
Ram132
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
saryu2011
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
javeed_mhd
 
Java Basics
Java BasicsJava Basics
Java Basics
Brandon Black
 
Core java
Core java Core java
Core java
Ravi varma
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
Vskills
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
Ganesh Chittalwar
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
Deniz Oguz
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Java tutorials
Java tutorialsJava tutorials
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
Bui Kiet
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Sagar Verma
 
Java Basics
Java BasicsJava Basics
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
Kernel Training
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep Dive
Martijn Dashorst
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
imypraz
 
Javatut1
Javatut1 Javatut1
Javatut1
desaigeeta
 

What's hot (20)

Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core java
Core java Core java
Core java
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 
Java Serialization Deep Dive
Java Serialization Deep DiveJava Serialization Deep Dive
Java Serialization Deep Dive
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
 
Javatut1
Javatut1 Javatut1
Javatut1
 

Viewers also liked

Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
Anton Keks
 
Android Mockup Toolkit
Android Mockup ToolkitAndroid Mockup Toolkit
Android Mockup Toolkit
Alan Goo
 
Animation in Java
Animation in JavaAnimation in Java
Animation in Java
Alan Goo
 
Bca i-fundamental of computer-u-4-data communication and network
Bca  i-fundamental of  computer-u-4-data communication and networkBca  i-fundamental of  computer-u-4-data communication and network
Bca i-fundamental of computer-u-4-data communication and network
Rai University
 
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
Gigaom
 
Soco java games 2011
Soco java games 2011Soco java games 2011
Soco java games 2011
鳳凰娛樂遊戲有限公司
 
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case StudyThe PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
Guerrilla
 
Advance Network Technologies
Advance Network TechnologiesAdvance Network Technologies
Advance Network Technologies
Dr Shashikant Athawale
 
Android Application And Unity3D Game Documentation
Android Application And Unity3D Game DocumentationAndroid Application And Unity3D Game Documentation
Android Application And Unity3D Game Documentation
Sneh Raval
 
Car Game - Final Year Project
Car Game - Final Year ProjectCar Game - Final Year Project
Car Game - Final Year Project
Vivek Naskar
 
Structure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Structure Data 2014: IS VIDEO BIG DATA?, Steve RussellStructure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Structure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Gigaom
 
OOP java
OOP javaOOP java
OOP java
xball977
 
Game project Final presentation
Game project Final presentationGame project Final presentation
Game project Final presentation
gemmalunney
 
Game Design: The Production Plan
Game Design: The Production PlanGame Design: The Production Plan
Game Design: The Production Plan
Kevin Duggan
 
Ppt.online games
Ppt.online gamesPpt.online games
Ppt.online games
meliza briones
 
Introduction to Game Development
Introduction to Game DevelopmentIntroduction to Game Development
Introduction to Game Development
Reggie Niccolo Santos
 
Game Development Step by Step
Game Development Step by StepGame Development Step by Step
Game Development Step by Step
Bayu Sembada
 
An Introduction To Game development
An Introduction To Game developmentAn Introduction To Game development
An Introduction To Game development
Ahmed
 
The Real-time Volumetric Cloudscapes of Horizon Zero Dawn
The Real-time Volumetric Cloudscapes of Horizon Zero DawnThe Real-time Volumetric Cloudscapes of Horizon Zero Dawn
The Real-time Volumetric Cloudscapes of Horizon Zero Dawn
Guerrilla
 
Big data ppt
Big data pptBig data ppt
Big data ppt
Thirunavukkarasu Ps
 

Viewers also liked (20)

Simple Pure Java
Simple Pure JavaSimple Pure Java
Simple Pure Java
 
Android Mockup Toolkit
Android Mockup ToolkitAndroid Mockup Toolkit
Android Mockup Toolkit
 
Animation in Java
Animation in JavaAnimation in Java
Animation in Java
 
Bca i-fundamental of computer-u-4-data communication and network
Bca  i-fundamental of  computer-u-4-data communication and networkBca  i-fundamental of  computer-u-4-data communication and network
Bca i-fundamental of computer-u-4-data communication and network
 
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
SMART TOOLS: DISSECT, DIGEST AND DELIVER BIG DATA from Structure:Data 2012
 
Soco java games 2011
Soco java games 2011Soco java games 2011
Soco java games 2011
 
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case StudyThe PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
The PlayStation®3’s SPUs in the Real World: A KILLZONE 2 Case Study
 
Advance Network Technologies
Advance Network TechnologiesAdvance Network Technologies
Advance Network Technologies
 
Android Application And Unity3D Game Documentation
Android Application And Unity3D Game DocumentationAndroid Application And Unity3D Game Documentation
Android Application And Unity3D Game Documentation
 
Car Game - Final Year Project
Car Game - Final Year ProjectCar Game - Final Year Project
Car Game - Final Year Project
 
Structure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Structure Data 2014: IS VIDEO BIG DATA?, Steve RussellStructure Data 2014: IS VIDEO BIG DATA?, Steve Russell
Structure Data 2014: IS VIDEO BIG DATA?, Steve Russell
 
OOP java
OOP javaOOP java
OOP java
 
Game project Final presentation
Game project Final presentationGame project Final presentation
Game project Final presentation
 
Game Design: The Production Plan
Game Design: The Production PlanGame Design: The Production Plan
Game Design: The Production Plan
 
Ppt.online games
Ppt.online gamesPpt.online games
Ppt.online games
 
Introduction to Game Development
Introduction to Game DevelopmentIntroduction to Game Development
Introduction to Game Development
 
Game Development Step by Step
Game Development Step by StepGame Development Step by Step
Game Development Step by Step
 
An Introduction To Game development
An Introduction To Game developmentAn Introduction To Game development
An Introduction To Game development
 
The Real-time Volumetric Cloudscapes of Horizon Zero Dawn
The Real-time Volumetric Cloudscapes of Horizon Zero DawnThe Real-time Volumetric Cloudscapes of Horizon Zero Dawn
The Real-time Volumetric Cloudscapes of Horizon Zero Dawn
 
Big data ppt
Big data pptBig data ppt
Big data ppt
 

Similar to Java Course 5: Enums, Generics, Assertions

Scala - core features
Scala - core featuresScala - core features
Scala - core features
Łukasz Wójcik
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala ntnu
Scala ntnuScala ntnu
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
Meetu Maltiar
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
Martin Odersky
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
Felipe
 

Similar to Java Course 5: Enums, Generics, Assertions (20)

Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 

More from Anton Keks

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
Anton Keks
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
Anton Keks
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
Anton Keks
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
Anton Keks
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
Anton Keks
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
Anton Keks
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
Anton Keks
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
Anton Keks
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
Anton Keks
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
Anton Keks
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
Anton Keks
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
Anton Keks
 

More from Anton Keks (13)

Being a professional software tester
Being a professional software testerBeing a professional software tester
Being a professional software tester
 
Java Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUIJava Course 14: Beans, Applets, GUI
Java Course 14: Beans, Applets, GUI
 
Java Course 13: JDBC & Logging
Java Course 13: JDBC & LoggingJava Course 13: JDBC & Logging
Java Course 13: JDBC & Logging
 
Java Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & ServletsJava Course 12: XML & XSL, Web & Servlets
Java Course 12: XML & XSL, Web & Servlets
 
Java Course 11: Design Patterns
Java Course 11: Design PatternsJava Course 11: Design Patterns
Java Course 11: Design Patterns
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, HibernateJava Course 15: Ant, Scripting, Spring, Hibernate
Java Course 15: Ant, Scripting, Spring, Hibernate
 
Choose a pattern for a problem
Choose a pattern for a problemChoose a pattern for a problem
Choose a pattern for a problem
 
Database Refactoring
Database RefactoringDatabase Refactoring
Database Refactoring
 
Scrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineerScrum is not enough - being a successful agile engineer
Scrum is not enough - being a successful agile engineer
 
Being a Professional Software Developer
Being a Professional Software DeveloperBeing a Professional Software Developer
Being a Professional Software Developer
 

Recently uploaded

Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
shyamraj55
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
Ivanti
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
HackersList
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
aslasdfmkhan4750
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
Google Developer Group - Harare
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
Shiv Technolabs
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Muhammad Ali
 
What's new in android: jetpack compose 2024
What's new in android: jetpack compose 2024What's new in android: jetpack compose 2024
What's new in android: jetpack compose 2024
Toru Wonyoung Choi
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
maigasapphire
 
Tailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer InsightsTailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer Insights
SynapseIndia
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
SubhamMandal40
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
Axel Rennoch
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
Ivanti
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
Baishakhi Ray
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
bellared2
 
Mastering OnlyFans Clone App Development: Key Strategies for Success
Mastering OnlyFans Clone App Development: Key Strategies for SuccessMastering OnlyFans Clone App Development: Key Strategies for Success
Mastering OnlyFans Clone App Development: Key Strategies for Success
David Wilson
 

Recently uploaded (20)

Integrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecaseIntegrating Kafka with MuleSoft 4 and usecase
Integrating Kafka with MuleSoft 4 and usecase
 
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-InTrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
TrustArc Webinar - 2024 Data Privacy Trends: A Mid-Year Check-In
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
 
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
High Profile Girls Call ServiCe Hyderabad 0000000000 Tanisha Best High Class ...
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
 
The Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF GuideThe Role of IoT in Australian Mobile App Development - PDF Guide
The Role of IoT in Australian Mobile App Development - PDF Guide
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
 
What's new in android: jetpack compose 2024
What's new in android: jetpack compose 2024What's new in android: jetpack compose 2024
What's new in android: jetpack compose 2024
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
 
Tailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer InsightsTailored CRM Software Development for Enhanced Customer Insights
Tailored CRM Software Development for Enhanced Customer Insights
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
Russian Girls Call Navi Mumbai 🎈🔥9920725232 🔥💋🎈 Provide Best And Top Girl Ser...
 
Mastering OnlyFans Clone App Development: Key Strategies for Success
Mastering OnlyFans Clone App Development: Key Strategies for SuccessMastering OnlyFans Clone App Development: Key Strategies for Success
Mastering OnlyFans Clone App Development: Key Strategies for Success
 

Java Course 5: Enums, Generics, Assertions

  • 1. Java course - IAG0040 Enums, Generics & Assertions Anton Keks 2011
  • 2. Arrays helper class ● Arrays class provides operations on arrays – asList() - provides a view of an array as a List – binarySearch() - searches for an element from a sorted array – equals() - checks two arrays for equality – fill() - fills an array with the specified element – sort() - sorts an array (using a tuned QuickSort algorithm) – toString() - can be used for displaying of arrays – deepToString() - the same for multidimensional arrays Java course – IAG0040 Lecture 5 Anton Keks Slide 2
  • 3. Collections helper class ● Provides constants and operations on Collections – EMPTY_XXX or emptyXXX() - immutable empty collection – sort(), binarySearch(), fill(), copy(), min(), max(), shuffle(), replaceAll(), rotate(), swap() – singletonXXX() - immutable collection with one element – enumeration() - for support of legacy classes ● Wrappers – checkedXXX() - a dynamically typesafe view – unmodifiableXXX() - an unmodifiable view – synchronizedXXX() - a synchronized view Java course – IAG0040 Lecture 5 Anton Keks Slide 3
  • 4. Tips ● Program to interfaces – List list = new ArrayList(); ● Copy (or conversion) constructors – Set set = new TreeSet(map.values()); ● Checking if the Collection is empty – collection.isEmpty() – collection.size() == 0 may be very expensive ● Remove all nulls (or other elements): – collection.removeAll(Collections.singleton(null)) ● Convert to arrays – String[] s = c.toArray(new String[c.size()]); Java course – IAG0040 Lecture 5 Anton Keks Slide 4
  • 5. Tips (cont) ● Iterate Maps with Map.Entry if you need both keys and values – for(Map.Entry e : map.entrySet()) {} ● Initial capacity in case of HashSet, HashMap, and ArrayList – new ArrayList(512) ● Operations on sublists are reflected in the main lists – list.subList(15, 16).remove(object); ● All collections implement toString() – useful for displaying the contents quickly Java course – IAG0040 Lecture 5 Anton Keks Slide 5
  • 6. Inner classes ● Inner classes can be defined inside of other classes – class MyClass { class InnerClass { } } – non static inner classes can access internals of parent classes – static inner classes cannot Java course – IAG0040 Lecture 5 Anton Keks Slide 6
  • 7. Anonymous inner classes ● Classes can be created and instantiated 'inline' – Runnable runnable = new Runnable() { public void run() { System.out.println("Running!"); } }; runnable.run(); ● Analogous to initialization of arrays: new byte[] {1} ● Very useful for implementation of short interfaces, where the code is needed as part of the surrounding code ● Compiled into ParentClass$1.class, where $1 is the index of the anonymous class within the ParentClass Java course – IAG0040 Lecture 5 Anton Keks Slide 7
  • 8. Annotations ● Annotations are special type of interfaces – @interface MyAnnotation { } – Allow specification of meta data for source code elements ● Used before the element in question, just like Javadoc – In general, don't have effect at runtime – Built-in: @SupressWarnings, @Deprecated, @Override, @Generated, etc – Can take parameters: @SupressWarnings(“unused”) or @SupressWarnings(value=“unused”) ● Very useful in various frameworks, e.g. JUnit4, Spring2, Hibernate3, EJB3 Java course – IAG0040 Lecture 5 Anton Keks Slide 8
  • 9. Enums ● Special type of class (base class is java.lang.Enum) ● enum Season {WINTER, SPRING, SUMMER, AUTUMN} ● Only one instance of each constant is guaranteed; enums cannot be instantiated; they are implicitly final (cannot be extended) ● Constructors can be used: WINTER(1), SPRING(“Hello”) ● Accessed like constants: Season.WINTER ● Every enum has the following methods: – int ordinal() - returns an ordinal value of the constant – String name() - returns the name of the constant – static Enum valueOf(String name) - returns the enum constant – static Season[] values() - returns an array of all constants ● See Season and Planet in net.azib.java.lessons.enums Java course – IAG0040 Lecture 5 Anton Keks Slide 9
  • 10. Introduction to Generics ● Are there any problems with collections? – String s = (String) list.get(3); ● Java 1.5 introduced generics for type safety checks – List<String> list; String s = list.get(3); ● Additionally, generics allow to abstract over types – List<Integer> list = Arrays.asList( new Integer[]{1,2}); – List<String> list = Arrays.asList( “a”, “b”, “c”); ● Provide more compile time information for error checking Java course – IAG0040 Lecture 5 Anton Keks Slide 10
  • 11. Defining generic classes ● public interface List<E> { void add(E x); Iterator<E> iterator(); } ● public interface Iterator<E>{ E next(); boolean hasNext(); } ● Formal type parameters are in the angle brackets <> ● In invocations of generic types (parametrized types), all occurrences of formal types are replaced by the actual argument ● Primitives cannot be used as arguments, but arrays and wrappers can – Iterator<int[]> i; List<Integer> intList; Java course – IAG0040 Lecture 5 Anton Keks Slide 11
  • 12. Defining generics ● Generics can be thought of as if they were expanded – public interface ListOfIntegers { void add(Integer x); Iterator<Integer> iterator(); } ● Actually they are not: generics introduce no memory or performance overhead ● Information about type parameters is stored in class files and used during compilation ● Use possibly meaningful single character names – E = Element, T = Type, K = Key, V = Value, etc Java course – IAG0040 Lecture 5 Anton Keks Slide 12
  • 13. Generics usage in Java API ● Collection<E>, Iterable<E>, Iterator<E> ● Set<E>, List<E>, Queue<E> – Set<String> set = new HashSet<String>(); – Queue<Dog> q = new LinkedList<Dog>(); ● Map<K, V> – Map<String, Thread> map = new HashMap<String, Thread>(); ● Comparator<T>, Comparable<T> ● Class<T> – Date d = Date.class.newInstance(); Java course – IAG0040 Lecture 5 Anton Keks Slide 13
  • 14. Subtyping ● If A extends B, does List<A> extend List<B>? ● List<String> ls = new ArrayList<String>(); List<Object> lo = ls; – this is illegal – List of Strings is not a List of Objects ● lo.add(new Integer(42)); // adds an illegal object String s = ls.get(0); // this is not a String! – this code would break type safety at runtime! ● However – ls instanceof List & lo instanceof List – Collection<String> cs = ls; // legal Java course – IAG0040 Lecture 5 Anton Keks Slide 14
  • 15. Backward compatibility ● Generics are backward compatible – Java 1.5 still had to be able to run old (unparameterized) code – Backward compatibility has influenced the implementation ● Old-style (unparameterized or raw-type) code can still be written – ArrayList al = new ArrayList<String>(); ArrayList<String> al = new ArrayList(); ● For now, checks are only done at compile time – At runtime, generic collections hold Objects ('type erasure') – Collections.checkedXXX() methods may be used for runtime type checking – Implementation may change in future Java course – IAG0040 Lecture 5 Anton Keks Slide 15
  • 16. Wildcards ● void printCollection(Collection<Object> c) { for (Object e : c) System.out.println(e); } ● printCollection(new ArrayList<String>()) // doesn't compile ● void printCollection(Collection<?> c) { // ? is a wildcard for (Object e : c) System.out.println(e); } ● However the following fails (at compile time!) – c.add(new Object()); – Collection<?> means “collection of unknown”, it is read-only – Unknown <?> can always be assigned to Object (when reading) Java course – IAG0040 Lecture 5 Anton Keks Slide 16
  • 17. Bounded wildcards ● <? extends T> means “anything that extends T” – upper bounded wildcard, “read-only” – List<? extends Number> vs List<Number> – List<Integer> can be assigned to the first one, but not to the second one – add() still doesn't work, because actual type is not known ● <? super T> means “anything that is a supertype of T” – lower bounded wildcard, “write-only” – List<? super Number> vs List<Number> – add(new Integer(5)) works, because Integer can be assigned to any supertype of Number or Number itself Java course – IAG0040 Lecture 5 Anton Keks Slide 17
  • 18. Generic methods ● Methods can also be generic, independently from their classes ● Generic methods can substitute wildcard types – boolean containsAll(Collection<?> c); <T> boolean containsAll(Collection<T> c); ● But it is more reasonable to use in case a type is used many times – <T> void copy(List<T> dest, List<? extends T> src); <T, S extends T> void copy( List<T> dest, List<S> src); ● T is selected automatically based on the passed types (it is always the most specific type possible), its usage is implicit ● Relative type dependencies are important (extends / super) Java course – IAG0040 Lecture 5 Anton Keks Slide 18
  • 19. Generics tasks ● Use generics in WordFrequencyCalculatorImpl and DuplicateRemoverImpl ● Write some new classes – Circle and Square ● both should extend the provided net.azib.java.lessons.collections.Shape – ShapeAggregatorImpl (which should implement the ShapeAggregator) Java course – IAG0040 Lecture 5 Anton Keks Slide 19
  • 20. Assertions ● assert keyword can be used for assertion of validity of boolean expressions (a debugging feature) – assert boolean-expression : value-expression; – assert A == 5 : “A is not 5!!!”; ● If boolean-expression evaluates to false, an AssertionError is thrown with the value-expression as detailed message (optional) ● Assertions are disabled by default, therefore have no runtime overhead ● When enabled, help to write self-documented code and trace bugs at runtime ● java -ea switch enables assertions (specific packages and classes may be specified if global activation is not desired) Java course – IAG0040 Lecture 5 Anton Keks Slide 20