SlideShare uma empresa Scribd logo
1 de 38
J2SE 5.0 Generics    ,[object Object],[object Object],[object Object]
Speaker’s Qualifications ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java SE 1.5 Language Changes
Seven Major New Features ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Generics
Is there a problem in here? Vector v = new Vector(); v.add(new  Integer (4)); OtherClass.expurgate(v); ... static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) if ((( String )it.next()).length() == 4) it.remove(); }
The Problem (Pre-J2SE 5.0) Vector v = new Vector(); v.add(new  Integer (4)); OtherClass.expurgate(v); ... static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) /*  ClassCastException   */ if ((( String )it.next()).length() == 4) it.remove(); }
Generics ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Using Generic Classes ,[object Object],[object Object],[object Object],[object Object],[object Object]
Wildcards ,[object Object],[object Object],[object Object],void printCollection(Collection <Object>  c) { for (Object o : c)  System.out.println( o ); }
Wildcards ,[object Object],[object Object],[object Object],void printCollection( Collection  <?>  c) { for (Object o : c)  System.out.println(o); }
Bounded Wildcards ,[object Object],public void  drawAll (List< ? extends Shape >s) { ... } List<Circle> c = getCircles(); drawAll(c) ; List<Triangle> t = getTriangles(); drawAll(t) ;
Autoboxing & Unboxing
Autoboxing/Unboxing of Primitive Types ,[object Object],[object Object],[object Object],[object Object],[object Object]
Autoboxing/Unboxing of Primitive Types ,[object Object],[object Object],[object Object],[object Object],[object Object]
Enhanced for Loop
Enhanced for Loop (foreach) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Enhanced for Loop Example ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Iterating over collections,  tricky, error prone ,[object Object],[object Object],[object Object]
Type-safe Enumerations
Type-safe Enumerations ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Enumeration Example: public class  Card  { public  enum   Suit  { spade, diamond, club, heart }; public  enum   Rank  {  ace, two, three, four, five,  six, seven, eight, nine, ten,  jack, queen, king }; private  Card (Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } } List< Card >  deck  = new ArrayList< Card >(); for ( Suit  suit :  Suit.values ()) for ( Rank  rank :  Rank.values ()) deck.add(new Card(rank, suit)); Think how much JDK1.4 code this would require!
Varargs
Before Varargs Example  //example method that takes a variable number of  parameters int sum( Integer[] numbers ) {  for(int i: numbers) // do something } // Code fragment that calls the sum method sum( new Integer[] {12,13,20} ); http://www.javaworld.com/javaworld/jw-04-2004/jw-0426-tiger1.html ,[object Object],[object Object]
Varargs Example  (Cont) //example method that takes a variable number of parameters int sum ( Integer... numbers )  { for(int i: numbers) // do something }  // Code fragment that calls the sum method sum( 12,13,20 ); http://www.javaworld.com/javaworld/jw-04-2004/jw-0426-tiger1.html ,[object Object],[object Object],[object Object]
Varargs examples ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Static Imports
Static Imports ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Formatted I/O
Simple Formatted I/O  ,[object Object],[object Object],[object Object],[object Object],[object Object]
Annotations
Annotations Metadata (JSR-175) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Annotations Example: JAX-RPC ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Resources and Summary
For More Information (1/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
For More Information (2/2) ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Resources ,[object Object],[object Object],[object Object]
Stay in Touch with Java SE  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thank You! ,[object Object],[object Object],[object Object]

Mais conteúdo relacionado

Mais procurados

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Java simple programs
Java simple programsJava simple programs
Java simple programsVEERA RAGAVAN
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenGraham Royce
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.David Gómez García
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)mehul patel
 
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 beyondMario Fusco
 

Mais procurados (20)

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Java programs
Java programsJava programs
Java programs
 
Java simple programs
Java simple programsJava simple programs
Java simple programs
 
Java practical
Java practicalJava practical
Java practical
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
Java programs
Java programsJava programs
Java programs
 
CS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUALCS2309 JAVA LAB MANUAL
CS2309 JAVA LAB MANUAL
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Thread
ThreadThread
Thread
 
Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.Java 8 Stream API. A different way to process collections.
Java 8 Stream API. A different way to process collections.
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
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
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 

Semelhante a Java Generics

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningCarol McDonald
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancementRakesh Madugula
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Raimon Ràfols
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Improving Android Performance at Mobiconf 2014
Improving Android Performance at Mobiconf 2014Improving Android Performance at Mobiconf 2014
Improving Android Performance at Mobiconf 2014Raimon Ràfols
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer iiIsabella789
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0Yaser Zhian
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumlercorehard_by
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasicswebuploader
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeMicrosoft Tech Community
 

Semelhante a Java Generics (20)

Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, TuningJava 5 6 Generics, Concurrency, Garbage Collection, Tuning
Java 5 6 Generics, Concurrency, Garbage Collection, Tuning
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015Improving Java performance at JBCNConf 2015
Improving Java performance at JBCNConf 2015
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
First fare 2010 java-introduction
First fare 2010 java-introductionFirst fare 2010 java-introduction
First fare 2010 java-introduction
 
Improving Android Performance at Mobiconf 2014
Improving Android Performance at Mobiconf 2014Improving Android Performance at Mobiconf 2014
Improving Android Performance at Mobiconf 2014
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 
How to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ CodeHow to Adopt Modern C++17 into Your C++ Code
How to Adopt Modern C++17 into Your C++ Code
 

Mais de Carol McDonald

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUsCarol McDonald
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Carol McDonald
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBCarol McDonald
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...Carol McDonald
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningCarol McDonald
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBCarol McDonald
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Carol McDonald
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareCarol McDonald
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningCarol McDonald
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Carol McDonald
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Carol McDonald
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churnCarol McDonald
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Carol McDonald
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient DataCarol McDonald
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APICarol McDonald
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesCarol McDonald
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataCarol McDonald
 

Mais de Carol McDonald (20)

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUs
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine Learning
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health Care
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep Learning
 
Spark graphx
Spark graphxSpark graphx
Spark graphx
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churn
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka API
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision Trees
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming Data
 

Último

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
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
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
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
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 

Último (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
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
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
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
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
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
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 

Java Generics

  • 1.
  • 2.
  • 3. Java SE 1.5 Language Changes
  • 4.
  • 6. Is there a problem in here? Vector v = new Vector(); v.add(new Integer (4)); OtherClass.expurgate(v); ... static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) if ((( String )it.next()).length() == 4) it.remove(); }
  • 7. The Problem (Pre-J2SE 5.0) Vector v = new Vector(); v.add(new Integer (4)); OtherClass.expurgate(v); ... static void expurgate(Collection c) { for (Iterator it = c.iterator(); it.hasNext();) /* ClassCastException */ if ((( String )it.next()).length() == 4) it.remove(); }
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 14.
  • 15.
  • 17.
  • 18.
  • 20.
  • 21. Enumeration Example: public class Card { public enum Suit { spade, diamond, club, heart }; public enum Rank { ace, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king }; private Card (Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } } List< Card > deck = new ArrayList< Card >(); for ( Suit suit : Suit.values ()) for ( Rank rank : Rank.values ()) deck.add(new Card(rank, suit)); Think how much JDK1.4 code this would require!
  • 23.
  • 24.
  • 25.
  • 27.
  • 29.
  • 31.
  • 32.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.

Notas do Editor

  1. Let&apos;s start then by looking at the new features included at the language level in J2SE 5
  2. This slide lists the seven new key features in J2SE 5. We&apos;ll describe each of these features. For generics and metadata we&apos;re going to go into a lot of detail to help you understand all of the issues around using these features correctly and effectively.
  3. Generics is a feature that has been requested many times in Java. Sun have had to be very careful about how to introduce this feature in a way that minimises the impact of compatability. As we&apos;ll see generics is a rather bad name for this feature since what we&apos;re really doing is allowing classes to be made type specific rather than type generic (which is really the situation that we have had all along in Java).
  4. OK, Lets take a look at Pre Java SE 5.0 code here. Can anyone tell if there is a problem here. Is it a compile time problem or a runtime problem? What problem? =&gt; Runtime exception
  5. This piece of code illustrates the problem in Java that generics addresses. A programmer has created a method called expurgate that takes a collection and removes all strings who&apos;s length is four characters from it. The method takes a Collection as a parameter and then iterates through all of the elements looking for four character strings. The Collection can hold objects of any type (meaning strictly speaking that it is generic - see the naming problem?) When we extract an element from the collection we need to do an explicit cast to tell the compiler the type of the object we&apos;re getting. This is dangerous, as we can see. A different programmer creates a Vector and rather than adding a String, adds an Integer object. This all compiles fine, as Integer is still a sub-class of Object which is the type of the argument for the add method. However, at run time when the code calls expurgate the VM will throw a ClassCastException since the Integer object is not a String or sub-type of String. This is bad because it is a runtime exception. This code could be running in a telco billing application where runtime exceptions mean potentially large loss of revenue. What we need is a way to tell the compiler, not the VM what type the collection is so that the compiler can check all uses and report an error when the code is compiled, not when it&apos;s running. This is what generics do.
  6. To restate the problem, the issue is that the compiler cannot check the types of the objects being stored in a collection because it has no way of knowing the type of the object, other than that it will be an Object or sub-type, which all classes by default are. All assignments when using the collections must do an explicit cast and can generate a runtime ClassCastException. The solution is for the programmer to give an explicit typing to a collection (or other class where this is required). By doing that the compiler can now check that all items added to a typed collection are correct. If we try to add an Integer to a String typed collection we will get a compiler error telling us that it is an inappropriate type. We can make the changes and prevent a runtime exception. The implementation of this feature is only in terms of compilation. The compiler is effectively adding the explicit cast for you and ensuring that only the correct type of obejcts are added. This is a key point from the perspective of compatability, which we&apos;ll discuss in more detail later. This is guaranteed to succeed from the point of view of eliminating ClassCastExceptions caused by this type of error. The asterisk is there because this will only hold true if all the code of an application is recompiled using the J2SE 5 compiler, so that all references can be checked. Pre 5.0 class files will still run using the new JVM. If you mix old and new class files you could still get a ClassCastException since the compiler will have been unable to check that the type of object being added to a collection is correct.
  7. In J2SE 5 all the collection classes (as well as many others) have been made generic. Here we look at the same example we had earlier that would have thrown a ClassCastException. Using generics, when we instantiate the Vector class we also include a type argument to tell the compiler that the Vector is only to be used to hold objects of type String (String is final so it&apos;s not possible to use a sub-class). If we then try and call the add method with an Integer object as a parameter the compiler will know this is wrong and will report an error. Lets declare another Vector, this time parameterised for Integer objects. If we return the comparison between the two Vectors what will the result be, true or false? The answer is true. The base type of the objects is still the same, they are both Vector and they both share the same class at runtime. The fact that one has been typed to hold Strings and one has been typed to hold Integers does not affect this comparison. This is an important fact to remember as we&apos;ll see later when we discuss type erasure.
  8. Well of course you all know that I wouldn&apos;t ask if the answer was yes. The problem is that A collection with the type argument of Objects is NOT a supertype of all types of collection. If you try to call this method and pass in a collection with type argument String you will get a compiler error due to the type mismatch. How do we therefore solve this problem? Invariant sub-typing: Collection&lt;Object&gt; is not a super-class of Collection&lt;String&gt; Remember earlier when we saw the comparison of the two references? The base types are the same, but parameters do not have inheritance in the same way as concrete classes.
  9. The answer is using what is called a wildcard type argument. This is the question mark that we saw earlier in the syntax definition for type arguments. The wildcard type is equivalent to saying the type is unknown, so Collection&lt;?&gt; is the same as saying a Collection of unknown type. This is also something important to remember as we&apos;ll see shortly
  10. There may be situations where we want to be able to define a type argument so that it is restricted to a particular class or sub-type of that class. Unlike normal classes, parameterised types do not have inheritance - we saw this earlier where a Collection of type String could not be treated as a sub-class of Collection of type Object. In this example we want to define a method that can draw a set of shapes taken from a List. Since we have a good OO design let&apos;s say we&apos;ve defined an interface called Shape which has concrete implementations called Circle and Triangle. If we defined the drawAll() method to take a List of type Shape we&apos;d get compiler errors trying to pass a List of Circle or Triangle objects.. We could use the wildcard type, but then we could pass any List to the method including ones that did not contain Shape objects. What we need to do is use a bounded wildcard, which is what we do here. We still use the wildcard type but we also specify that it extends Shape. This means that only a List typed to contain objects that are a sub-class of Shape can be passed as a parameter (remember that Shape is a sub-class of itself). Our example will compile and work as we want it to do.
  11. Generics is a feature that has been requested many times in Java. Sun have had to be very careful about how to introduce this feature in a way that minimises the impact of compatability. As we&apos;ll see generics is a rather bad name for this feature since what we&apos;re really doing is allowing classes to be made type specific rather than type generic (which is really the situation that we have had all along in Java).
  12. The first feature is what&apos;s called autoboxing and unboxing. Java is an object oriented language, but to purist like Smalltalk developers it&apos;s not truly object oriented as it still has primitive types to represent numbers and booleans. The reason for including these is that if everything is treated as an object you will never be able to get the application to perform as well as natively compiled C and C++ code. The problem with primitives is that in order to store them in a collection they have to be made into an object. Java provides the wrapper classes like Integer and Short for this purpose. To add a primitive to a collection is therefore complex as we must first instantiate a new wrapper class object and then add it to the collection. Similarly when getting the value out of the collection we first must retrieve the wrapper object and then call the appropriate method. Auto-boxing and unboxing solves this problem by letting the compiler do the hard work for us. As we can see in the example we can simply assign the value 22 to the Byte wrapper class object. The compiler will instantiate the object for us. We can do this because Java does not support explicit pointers. In C or C++ we wouldn&apos;t know whether this was assigning the memory address 22 to this object reference. Since in Java you cannot do that, the compiler knows it must be an auto-boxing conversion. Similarly when we want to get the value back we simply say int i = byteObj and the compiler fills in the method call for us. This will also work in method calls so we can simply pass the value 22 to the add method of ArrayList and the compiler will replace that with add(new Integer(22)).
  13. The first feature is what&apos;s called autoboxing and unboxing. Java is an object oriented language, but to purist like Smalltalk developers it&apos;s not truly object oriented as it still has primitive types to represent numbers and booleans. The reason for including these is that if everything is treated as an object you will never be able to get the application to perform as well as natively compiled C and C++ code. The problem with primitives is that in order to store them in a collection they have to be made into an object. Java provides the wrapper classes like Integer and Short for this purpose. To add a primitive to a collection is therefore complex as we must first instantiate a new wrapper class object and then add it to the collection. Similarly when getting the value out of the collection we first must retrieve the wrapper object and then call the appropriate method. Auto-boxing and unboxing solves this problem by letting the compiler do the hard work for us. As we can see in the example we can simply assign the value 22 to the Byte wrapper class object. The compiler will instantiate the object for us. We can do this because Java does not support explicit pointers. In C or C++ we wouldn&apos;t know whether this was assigning the memory address 22 to this object reference. Since in Java you cannot do that, the compiler knows it must be an auto-boxing conversion. Similarly when we want to get the value back we simply say int i = byteObj and the compiler fills in the method call for us. This will also work in method calls so we can simply pass the value 22 to the add method of ArrayList and the compiler will replace that with add(new Integer(22)).
  14. Generics is a feature that has been requested many times in Java. Sun have had to be very careful about how to introduce this feature in a way that minimises the impact of compatability. As we&apos;ll see generics is a rather bad name for this feature since what we&apos;re really doing is allowing classes to be made type specific rather than type generic (which is really the situation that we have had all along in Java).
  15. The next new feature is the enhanced for loop, If we have a collection and want to iterate over all the elements we use a for loop and an Iterator object. This is potentally error prone as the for loop has three parts to it initialisation, test and increment. The iterator can be used in all three of these places; if cut and paste is used incorrectly or an identifier is mis-typed some very subtle and hard to find bugs can be introduced. The solution is to let the compiler do the hard work for you again. To do this, the for loop has had a new syntactical construct added. Rather than using the traditional three statements separated by semi-colons, we have a single statement of the form variable defintiion colon collection name. This tells the compiler that we want to iterate over the collection specified and will use the variable identifier within the loop to reference each item. This sytax will work either for a collection or for an array.
  16. Here we see a good example of old and new style programming. We have a method that is designed to cancel a set of timer tasks. In the old code we would need to retrieve the Iterator from the collection passed as a parameter, which is the initialisation of the for loop. The test of the for loop uses the hasNext method of the iterator and then within the body of the foor loop we use the next method to retrieve the element. We also need to do an explicit cast so that the object retrieved from the collection can be assigned to the correct type. Obvioulsy, this is rather verbose and prone to errors when using the same Iterator three times. The new code makes this much simpler. We simply use the new for loop construct to define a variable, task that will be used in the body of the for loop, being of type TimerTask and iterating over the collection passed in, c. We then simply call the cancel method on task. We&apos;re also using generics in this example to tell the compiler the type of the collection.
  17. Generics is a feature that has been requested many times in Java. Sun have had to be very careful about how to introduce this feature in a way that minimises the impact of compatability. As we&apos;ll see generics is a rather bad name for this feature since what we&apos;re really doing is allowing classes to be made type specific rather than type generic (which is really the situation that we have had all along in Java).
  18. Often there are times when a programmer wants to have a variable that can only hold one of a fixed set of values. Typically we do this by assigning a number to each value and then storing it as an integer, using final static defintitions to assign the appropriate values. This is not a reliable mechanism which is why J2SE has introduced type safe enumerations. An enumeration is a new kind of class definition which uses the keyword enum to differentiate it from a normal class. Even though an enumeration is like a class in many way, it is not the same. You cannot instantiate an enumeration; this is effectively done once by the VM when the system. The definition of an enumeration contains a set of public, self-typed members which are used as the constants of that type. These values can be used in a switch statement with the case keyword. Previously all values used with a case statement had to be integers.(Sang: so you can do swtich statement with a typed object?) The compiler will handle the use of the enumeration correctly. With the introduction of enumerations Java now has a new reserved word, enum. This is a consideration from a migration perspective since any code using enum as an identifier will need to be changed to compile under J2SE 5.
  19. First example of the use of an enumeration. This code uses two simple enumerations to represent the cards in a pack. One enumeration is used for the suits and one is used for the values. The definition is very simple, we just define the enumeration as having the constants we want separated by commas. We can then refer to these constants in our program, for example in a switch statement. For this example we create an ArrayList to hold the pack of cards. We use a type argument to tell the compiler that we want this List to only hold objects of type Card (which is defined elsewhere). We can then use the new for loop construct to iterate over the enumerations, populating the list. Notice the use of the values() method to return a collection of the constants of the enumeration. Finally we shuiffle the deck using the shuffle() utility method of the Collections class. Using a combination of features from J2SE 5 we can see that code can become much more concise, easy to read and easy to maintain. Imagine writing this code in pre J2SE 5 Java; it would take 3 or 4 times as much code
  20. .
  21. Generics is a feature that has been requested many times in Java. Sun have had to be very careful about how to introduce this feature in a way that minimises the impact of compatability. As we&apos;ll see generics is a rather bad name for this feature since what we&apos;re really doing is allowing classes to be made type specific rather than type generic (which is really the situation that we have had all along in Java).
  22. Java has always supported import declarations that allow types from other packages to be referred to using their simple names, i.e. without using a fully qualified class name. However, the static members of classes have not been treated in the same way; for example, whenever you refer to a static member of the Color class it&apos;s necessary to explicitly state Color.yellow or Color.blue. In J2SE 5 the import mechanism has been extended to include static members. To use this the static keyword is added to the normal import to indicate that static members can be accessed without specifying the class name. As with normal imports the wildcard * can be used to indicate all members of the package. The import applies to all static members of the class including methods and enums.
  23. Lets look at some of the changes and new features in the Java Virtual Machine
  24. Now that Java supports varargs, the much loved (or maligned) printf library call has been added that will be familiar to C and C++ programmers. If you have not used these languages before you will want to have a look at the manual page to see exactly how to use this. printf takes a string as an argument that will be displayed on the standard output. This string can contain arguments identified by the % character that will be replaced by the values of the other arguments when the string is displayed. The order of the arguments in the string must match the order of the arguments in the method call. The % character is followed by characters to indicate what type the argument is and how it should be formatted for display. For example, %s indicates a free format string; %2.2F indicates a floating point number that should have two digits before and after the decimal point. Since Java is cross platform you can use %n to specify a newline that will be correct for the current OS. and can still be used, but these will only output carriage return and linefeed. The scanf function that is the inverse of printf has not been included. The Scanner class provides a simple text scanner which can parse primitive types and strings using regular expressions. A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. In the example shown, the code allows a user to read a number from System.in
  25. Lets look at some of the changes and new features in the Java Virtual Machine
  26. Metadata allows programmer to specify annotations for parts of a program. An annotation is a modifier consisting of an annotation type and zero or more element-value pairs, each of which associates a value with a different element of the annotation type. The purpose of an annotation is simply to associate information with the annotated program element. Annotations can be used by tools such as compilers, IDEs and runtime tools to produce derived files, whether that is something like a new source file, a deployment descriptor or some other file. Java already has some annotations, but these are not organised in a formal way, which is what metadata does. For example, the Serializeable interface contains no methods. If you create a class that implements Serializeable, what does it do? The answer is that implementing the interface is used as a marker (or annotation) to tell the compiler that this class can be serialised. The compiler will then add apropriate code to perform serialisation when required. Xdoclets is another example of a form of annotation that can be used to derive deployment descriptors, etc from infromation contained in the source file. Annotations may be used as modifiers in any declaration, whether package, class, interface, field, method, parameter, constructor, or local variable. Annotations may also be used on enum constants. Such annotations are placed immediately before the enum constant they annotate.