MELJUN CORTES Java Lecture Java 5 New Features

Post on 13-May-2015

180 views 1 download

Tags:

description

MELJUN CORTES Java Lecture Java 5 New Features

Transcript of MELJUN CORTES Java Lecture Java 5 New Features

New Java 5 New Java 5 FeaturesFeatures

Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming

The Complete Java Boot CampThe Complete Java Boot Camp

MELJUN CORTESMELJUN CORTES

MELJUN CORTESMELJUN CORTES

The Big StuffThe Big Stuff

GenericsGenerics EnumerationsEnumerations New concurrency constructsNew concurrency constructs New interfacesNew interfaces AutoboxingAutoboxing New loop “for/in”New loop “for/in”

Less Big StuffLess Big Stuff

Static importsStatic imports varargsvarargs System.lang.FormatterSystem.lang.Formatter AnnotationsAnnotations JVM monitoring and controlJVM monitoring and control

GenericsGenerics

Java Generics were strongly driven by Java Generics were strongly driven by desire for less fiddly Collections desire for less fiddly Collections programming.programming.

Like C++ templates, provide compile-time Like C++ templates, provide compile-time resolution of datatype abstractions that resolution of datatype abstractions that preserve type safety and eliminate need for preserve type safety and eliminate need for casting.casting.

GenericsGenerics

Can employ generics in classes, interfaces Can employ generics in classes, interfaces and methods.and methods.

Unlike C++ templates, Generics are more Unlike C++ templates, Generics are more than a clever macro processor: Java than a clever macro processor: Java compiler keeps track of generics internally, compiler keeps track of generics internally, and uses same class file for all instances.and uses same class file for all instances.

Six core collections interfaces Six core collections interfaces are synchronization wrappers:are synchronization wrappers: CollectionCollection abstract generic abstract generic

classclass ListList Set, SortedSetSet, SortedSet Map, SortedMapMap, SortedMap

Non-generic collections classes Non-generic collections classes (HashMap(HashMap, etc.) still, etc.) still available, of available, of course.course.

Generic CollectionsGeneric Collections

Java 1.4 :Java 1.4 :

Simplify Collections UseSimplify Collections Use

●Java 1.5:

LinkedList list = new LinkedList();list.add(new Integer(1));Integer num = (Integer) list.get(0);

LinkedList<Integer> list = new LinkedList<Integer>();list.add(new Integer(1));Integer num = list.get(0);

Simplify Collections UseSimplify Collections Use

OriginalOriginal

HashMap celebrityCrashers = new HashMap();celebrityCrashers.put( new Date( “10/05/2005” ), new String( “Lindsay Lohan” ) );

Date key = new Date( "10/1/2005" );if ( celebrityCrashers.containsKey( key ) ){ System.out.println( "On " + key + “, “ +(String) celebrityCrashers.get( key ) + “crashed a vehicle.");}

Simplify Collections UseSimplify Collections Use

Hot and CrispyHot and Crispy

Map<Date,String> celebrityCrashers = new HashMap<Date,String>();celebrityCrashers.put( new Date(“10/05/2005”), new String( “Lindsay Lohan” ) );

Date key = new Date("10/05/2005");if ( celebrityCrashers.containsKey( key ) ) { System.out.printf( "On %tc, %d crashed a vehicle%n”, key, celebrityCrashers.get( key ) );

Defining GenericsDefining Generics ClassesClasses

●Interfaces

●Methods

class LinkedList<E> implements List<E> { // implementation }

interface List<E> { void add(E x); Iterator<E> iterator();}

void printCollection(Collection<?> c) { for(Object o:c) { System.out.println(o); }}

WildcardsWildcards

? extends Type? extends Type – a family of Type – a family of Type subtypessubtypes

? super Type? super Type – a family of Type – a family of Type supertypessupertypes

?? - the set of all Types, or - the set of all Types, or anyanypublic static <T extends Comparable<? super T>> void sort(List<T> list) { Object a[] = list.toArray(); Arrays.sort(a); ListIterator<T> i = list.listIterator(); for(int j=0; j<a.length; j++) { i.index(); i.set((T)a[j]); }}

EnumerationsEnumerations In Java 1.4: 'type safe enum' design pattern:In Java 1.4: 'type safe enum' design pattern:// This class implements Serializable to preserve valid equality// tests using == after deserialization.

public final class PowerState implements java.io.Serializeable { private transient final String fName; private static int fNextOrdinal = 1; private final int fOrdinal = fNextOrdinal++;

private PowerState(String name) { this.fName = name; }

public static final PowerState ON = new PowerState("ON"); public static final PowerState OFF = new PowerState("OFF");

public String toString() { return fName; }

private static final PowerState[] fValues = {ON, OFF}; private Object readResolve () throws java.io.ObjectStreamException{ return fValues[fOrdinal]; }}

EnumerationsEnumerations

A bit more concise in Java 5:A bit more concise in Java 5:

public enum PowerState {ON, OFF};

●Enum classes:– declare methods values(), valueOf(String)

– implement Comparable, Serializeable

– override toString(), equals(), hashCode(), compareTo()

java.util.concurrentjava.util.concurrent

New package that supports concurrent New package that supports concurrent programmingprogramming

Executor interface executes a RunnableExecutor interface executes a Runnable ThreadPoolExecutor class allows creation ThreadPoolExecutor class allows creation

of single, fixed and cached thread poolsof single, fixed and cached thread pools Executor also executes Callable objects. Executor also executes Callable objects.

Unlike Runnable, Callable returns a result Unlike Runnable, Callable returns a result and can throw exceptionsand can throw exceptions

AutoboxingAutoboxing

Easier conversion between primative and Easier conversion between primative and reference typesreference types

// Java 1.4

List numbers = new ArrayList();numbers.add(new Integer(-1));int i = ((Integer)numbers.get(0)).intValue();

// Java 5

List numbers = new ArrayList();numbers.add(-1); // Box int to Integerint i = numbers.get(0); // Unbox Integer to int

Static ImportsStatic Imports

Langauge support makes it easier to import Langauge support makes it easier to import static members from another class. No static members from another class. No more BigBagOf Constants interfaces. more BigBagOf Constants interfaces.

import static java.lang.Math.*;

... int x = round(4.5f); ...

Enhanced Enhanced for Loopfor Loop

Collection<Integer> temperatures = new LinkedHashSet<Integer>();

temperatures.add(105);temperatures.add(92);temperatures.add(7);

for(Integer aTemp : temperatures) { System.out.println("This temperature is " + aTemp);} Hides the loop counter or Iterator....Hides the loop counter or Iterator.... ...but therefore can't be used when your ...but therefore can't be used when your

code needs the counter or Iterator.code needs the counter or Iterator.

Variable Argument ListVariable Argument List

public int min(int first, int... rest) { int min = first;

for(int next: rest){ if (next < min) min = next; } return min;}

varargs mechanism allows variable length argument varargs mechanism allows variable length argument lists. lists.

java.util.Formatter Classjava.util.Formatter Class

Provides control of string formatting akin to Provides control of string formatting akin to C's printf()C's printf()

Utilizes a format string and format Utilizes a format string and format specifiersspecifiers

Unlike C format strings, note use of “%” as Unlike C format strings, note use of “%” as sole format specifier. No backslashes, such sole format specifier. No backslashes, such as “\n”as “\n”

System.out.printf(“%s crashed on %tc%n”, celebName, crashDate);

AnnotationsAnnotations

Let you associate metadata with program Let you associate metadata with program elementselements

Annotation name/value pairs accessible Annotation name/value pairs accessible through Reflection APIthrough Reflection API

Greatest utility is to tools, such as code Greatest utility is to tools, such as code analyzers and IDEs. JDK includes analyzers and IDEs. JDK includes apt tool apt tool that provides framework for annotation that provides framework for annotation processing tools.processing tools.

AnnotationsAnnotations

Most useful annotation to programmer:Most useful annotation to programmer:@Override@Override

interface Driver { //...

int getDrivingSkillsIndex();}

public class Celebrity implements Driver { //...

/** * The @Override annotation will let the compiler * catch the misspelled getDrivinSkillsIndex(). */ @Override getDrivinSkillsIndex() { return 0; }

//...

AnnotationsAnnotations

Next most useful annotations to Next most useful annotations to programmers:programmers:@Deprecated, @SuppressWarnings@Deprecated, @SuppressWarnings

@Deprecated public class BuggyWhip{ ... }

//...

// @SuppressWarnings selectively turns off javac warnings// raised by use of the -Xlint option

@SuppressWarnings({“fallthrough”})public void iUseSloppySwitchCoding { ... };

AnnotationsAnnotations

You can define your own (e.g., to supplant You can define your own (e.g., to supplant javadoc tags, or annotate for code javadoc tags, or annotate for code management practices)management practices)

See Chapter 4 of Java In A NutshellSee Chapter 4 of Java In A Nutshell

Monitoring & ManagementMonitoring & Management

JMX API (javax.management) provides remote JMX API (javax.management) provides remote monitoring and management of applicationsmonitoring and management of applications

java.lang.management uses JMX to define java.lang.management uses JMX to define MXBean interfaces for monitoring and managing MXBean interfaces for monitoring and managing a running JVMa running JVM

MXBean interface lets you monitor class MXBean interface lets you monitor class loadings, compilation times, garbage loadings, compilation times, garbage collections, memory, runtime configuration and collections, memory, runtime configuration and thread info.thread info.

MXBean also provides for granting of JVM MXBean also provides for granting of JVM monitoring and control permissionmonitoring and control permission

Monitoring & ManagementMonitoring & Management

java.lang.instrument defines the API to define java.lang.instrument defines the API to define agents that instrument a JVM by transforming class agents that instrument a JVM by transforming class files to add profiling support, code coverage files to add profiling support, code coverage testingtesting

Instrumentation agent classes define Instrumentation agent classes define premain() premain() method, which is called during startup before method, which is called during startup before main() for each agent class specified on the Java main() for each agent class specified on the Java interpreter command lineinterpreter command line

Instrumentation object can register Instrumentation object can register ClassFileTransformer objects to rewrite class file ClassFileTransformer objects to rewrite class file byte codes as they're loaded.byte codes as they're loaded.

References & CreditsReferences & Credits

Sun J2SE 5 tutorial Sun J2SE 5 tutorial http://java.sun.com/developer/technicalArticles/J2SE/generics/

Java 5 In A Nutshell (O'Reilly's Nutshell Series)Java 5 In A Nutshell (O'Reilly's Nutshell Series) ““A quick tour 'round Java 5”A quick tour 'round Java 5”

http://www.clanproductions.com/java5.html ““Type Safe Enumerations”Type Safe Enumerations”

http://www.javapractices.com/Topic1.cjp#Legacyhttp://www.javapractices.com/Topic1.cjp#Legacy