meljun cortes java lecture java5 new features
TRANSCRIPT
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
1/26
New Java 5FeaturesJava Fundamentals and Object-Oriented
Programming
The Complete Java Boot Camp
MELJUN CORTES
MELJUN CORTES
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
2/26
The Big Stuff Generics
Enumerations
New concurrency constructs
New interfaces
Autoboxing
New loop for/in
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
3/26
Less Big Stuff
Static imports
varargs
System.lang.Formatter
Annotations
JVM monitoring and control
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
4/26
Generics Java Generics were stron gly d r iven by
desire for less f idd ly Col lect ions
programming.
Like C++ temp lates, prov ide com pile-t ime
reso lut ion of datatype abstract ions that
preserve type safety and el im inate need fo r
cast ing.
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
5/26
GenericsCan emplo y generics in classes, interfaces
and method s.
Unlik e C++ temp lates, Generics are more
than a clever macro processor: Java
compiler keeps track o f generics in ternally,
and uses same class f i le for al l instances.
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
6/26
Six core collections interfacesare synchronization wrappers:
Collectionabstract generic
class List
Set, SortedSet
Map, SortedMap
Non-generic collections classes(HashMap, etc.) stillavailable, of
course.
Generic Collections
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
7/26
Java 1.4 :
Simplify Collections Use
Java 1.5:
LinkedList list = new LinkedList();list.add(new Integer(1));Integer num = (Integer) list.get(0);
LinkedList list= new LinkedList();
list.add(new Integer(1));Integer num = list.get(0);
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
8/26
Simplify Collections Use
Original
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.");
}
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
9/26
Simplify Collections Use
Hot and Crispy
Map celebrityCrashers= new HashMap();
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 ) );
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
10/26
Defining Generics
Classes
Interfaces
Methods
class LinkedList implements List {// implementation
}
interface List {void add(E x);Iterator iterator();
}
void printCollection(Collection c) {for(Object o:c) {
System.out.println(o);}
}
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
11/26
Wildcards ? extends Typea family of Type
subtypes
? super Typea family of Typesupertypes
?- the set of all Types, or anypublic static
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
12/26
Enumerations 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];
}}
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
13/26
Enumerations 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()
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
14/26
java util concurrent New package that supports concurrent
programming
Executor interface executes a Runnable
ThreadPoolExecutor class allows creationof single, fixed and cached thread pools
Executor also executes Callable objects.
Unlike Runnable, Callable returns a resultand can throw exceptions
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
15/26
Autoboxing Easier conversion between primative and
reference 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
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
16/26
Static Imports
Langauge support makes it easier to importstatic members from another class. Nomore BigBagOf Constants interfaces.
import static java.lang.Math.*;
...
int x = round(4.5f);...
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
17/26
Enhanced for oopCollection temperatures
= new LinkedHashSet();
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....
...but therefore can't be used when yourcode needs the counter or Iterator.
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
18/26
Variable 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 argumentlists.
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
19/26
java.util.Formatter Class
Provides control of string formatting akin toC's printf()
Utilizes a format string and formatspecifiers
Unlike C format strings, note use of % assole format specifier. No backslashes, such
as \nSystem.out.printf(%s crashed on %tc%n,
celebName, crashDate);
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
20/26
Annotations Let you associate metadata with program
elements
Annotation name/value pairs accessible
through Reflection API
Greatest utility is to tools, such as codeanalyzers and IDEs. JDK includes apt too lthat pro vides framework fo r annotat ion
process ing tools .
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
21/26
Annotations Most useful annotation to programmer:@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; }
//...
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
22/26
Annotations
Next most useful annotations toprogrammers:@Deprecated, @SuppressWarnings
@Deprecated public class BuggyWhip{ ... }
//...
// @SuppressWarnings selectively turns off javac warnings// raised by use of the -Xlint option
@SuppressWarnings({fallthrough})public void iUseSloppySwitchCoding { ... };
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
23/26
AnnotationsYou can define your own (e.g., to supplant
javadoc tags, or annotate for codemanagement practices)
See Chapter 4 of Java In A Nutshell
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
24/26
Monitoring & Management
JMX API (javax.management) provides remotemonitoring and management of applications
java.lang.management uses JMX to define
MXBean interfaces for monitoring and managinga running JVM
MXBean interface lets you monitor classloadings, compilation times, garbagecollections, memory, runtime configuration andthread info.
MXBean also provides for granting of JVMmonitoring and control permission
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
25/26
Monitoring & Management
java.lang.instrument defines the API to defineagents that instrument a JVM by transforming classfiles to add profiling support, code coveragetesting
Instrumentation agent classes define premain()method, which is cal led dur ing startup before main()
for each agent class speci f ied on the Java
interpreter command l ine
Ins trumentat ion object can registerClassFi leTrans former ob jects to rewri te class f i le
by te codes as they're loaded.
-
8/13/2019 MELJUN CORTES JAVA Lecture Java5 New Features
26/26
References & Credits
Sun J2SE 5 tutorialhttp://java.sun.com/developer/technicalArticles/J2SE/generics/
Java 5 In A Nutshell (O'Reilly's Nutshell Series)
A quick tour 'round Java 5http://www.clanproductions.com/java5.html
Type Safe Enumerationshttp://www.javapractices.com/Topic1.cjp#Legacy
http://java.sun.com/developer/technicalArticles/J2SE/generics/http://www.clanproductions.com/java5.htmlhttp://www.clanproductions.com/java5.htmlhttp://www.clanproductions.com/java5.htmlhttp://java.sun.com/developer/technicalArticles/J2SE/generics/http://java.sun.com/developer/technicalArticles/J2SE/generics/