1. Important language changes
l generics
l Enhanced cycle (Foreach)
l Autoboxing and unboxing
l Security type enums
l varargs
l Static Import
l annotations
2, generics
(1) problem
l When you get an element from a collection, you must perform type conversion:
Ø Type conversion is trouble
Ø Type conversion is unsafe, may fail during runtime
l Why can't you do better: tell the type of element in the compiler collection?
Ø Let the compiler join the type conversion function
Ø Compiler will guarantee the success of type conversion
(2) Example of filtration set
// Removes 4-Letter Words from C; Elements Must Be Strings
Static void Expurgate (Collection C) {
Iterator i = C.ITERATOR (); I.hasnext ();) {
String s = (string) i.next ();
IF (s.Length () == 4) {
I.Remove ();
}
}
}
(3) Using generics
// Removes 4-Letter Words from C
Static void ExpurGate (Collection
Item
IF (i.next (). Length () == 4) {
I.Remove ();
}
}
}
l is more clear and safe
l There is no type conversion, additional parentheses and temporary variables
l Provides type checking time
(4) Wide type is not a template
l There is no expansion code
l No terrible complexity
l No template program
l Simplely providing time-translation type security and elimination type conversion
3, enhanced cycles (Foreach)
(1) problem
l Traversal collection is trouble
l Iterator usually only used when the element is acquired
l Use item to tend to errors:
Ø Iterator variables appear 3 times in the loop
Ø Make you a chance to make two mistakes
Ø Usually copy paste error
l Why don't you do better, if you can make the compiler to handle itemarator?
(2) Examples of usually accessing collective elements
Void Cancelall (Collection C) {
Iterator i = C.ITERATOR (); I.hasnext ();) {
TIMERTASK TT = (Timertask) i.next ();
Tt.cancel ();
}
}
(3) Examples using enhanced cycles
Void Cancelall (Collection C) {
For (Object O: C) {
(TIMERTASK) o) .cancel ();
}
}
l is more clear and safe
L and Iterator
l Items that cannot use errors
(4) Examples of combined generics
Void Cancelall (Collection
For (Timertask Task: c) {
Task.cancel ();
}
}
l is more simple, clear and safe
l Code accurately express what it has to do
(5) The same suitable for arrays
// Returns the Sum of the Elements of A
Int sum (int [】 a) {
Int results = 0;
For (INT I: a) {
Result = i;
}
Return Result;
}
l Eliminate errors that use array indexes
l has the advantages described above
(6) Flexible nested Iterator
l usually example
List suits = ...;
List ranks = ...;
List sorteddeck = new arraylist ();
// Broken - throws nosuchelementexception!
Iterator i = suits.iterator (); I.hasnext ();) {
Iterator j = ranks.Itemrator (); j.hasnext ();) {
sorteddeck.add (new card (i.next (), j.ness ()));
}
}
// fixed - a bit ugly
Iterator i = suits.iterator (); I.hasnext ();) {
Suit suit = (suit) i.next ();
Iterator j = ranks.Itemrator (); j.hasnext ();) {
sorteddeck.add (new card (suit, j.ness ())));
}
}
l Simple and flexible use enhancement cycle
Suit suit: suits) {
For (Rank Rank: Ranks) {
SortedDeck.Add (New Card (Suit, Rank));
}
}
4, automatic sealing, unboxing)
(1) problem
l Cannot put int in the collection, you must use Integer
l The income of the income is income when getting
l Isn't it better by the compiler?
(2) Use the usual method to create an example of a frequency table
PUBLIC CLASS FREQ {
Private static final integer one = new integer (1);
Public static void main (String [] args) {
// Maps Word (String) to Frequency (Integer)
Map m = new trends ();
For (int i = 0; i Integer Freq = (Integer) M.GET (Args [i]); M.PUT (args [i], (freq == null? one: new integer FREQ.IntValue () 1))))) } System.out.println (m); } (2) Examples of combining automatic sealing, generic and enhanced cycles PUBLIC CLASS FREQ { Public static void main (String [] args) { Map For (String Word: args) { Integer freq = m.get (Word); M.PUT (Word, (freq == NULL? 1: FREQ 1); } System.out.println (m); } } 5, secure type enums (1) Standard INUM mode Public class almanac { Public static final int season_winter = 0; Public static final int season_spring = 1; Public static final int season_summer = 2; Public static final int season_fall = 3; ... // Remainder Omitted } l Disadvantages: Ø Not safe type Ø No namespace: there must be a constant prefix Ø Vulnerability: constant is compiled into the client program Ø Printable value does not provide information (2) Example of the ENUM mode of safety type Import java.io.serializable; Import java.util.Arrays; Import java.util.collections; Import java.util.list; Public Final Class Season IMPLEments Comparable, Serializable { PRIVATE FINAL STRING NAME; Public string toString () { Return Name; } Private season (String name) { THIS.NAME = Name; } Public Static Final Season Winter = New Season ("Winter"); Public Static Final Season Spring = New Season ("Spring"); Public Static Final Season Summer = New Season ("SUMMER"); Public Static Final Season Fall = New Season ("Fall"); Private static int nextordinal = 0; PRIVATE FINAL INT ORDINAL = Nextordinal ; Public int compareto (Object O) { Return Ordinal - (Season O) .ordinal; } Private static final season [] private_values = {winter, spring, summer, Fall}; Public Static Final List Values = Collectes.unmodifiableList (Arrays .slist (private_values)); private object readresolve () { // canonicalize Return private_values [Ordinal]; } } l Basic idea: use the constant of exporting custom types, no public constructing method l Fix all the shortcomings above l Other advantages: Ø Can add any method, domain variable Ø Enable interface l Disadvantages: Ø Code length Ø Easy to error: 3 times each constant Ø Can not be used in Switch statements l Why can't you do better, by the compiler? (3) Safety type Enum structure l Compiler supports secure types of ENUM mode l Similar to typical enums (like C, C ) Ø Enum season {Winter, Spring, Summer, Fall} l More powerful: Ø All the advantages of the secure type ENUM mode Ø Can be used in Switch statements (4) ENUM examples in combination with generic and enhanced cycles ENUM Suit {Clubs, Diamonds, Hearts, Spades} ENUM RANK {Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace} List Suit suit: suit.values ()) { For (Rank Rank: rank.values ()) { Deck.add (New Card (Suit, Rank); } } Collects.shuffle (DECK); (5) ENUM examples of domain variables, methods and construction methods Public enum coin { Penny (1), Nickel (5), DIME (10), Quarter (25); Coin (int value) { THIS.VALUE = VALUE; } PRIVATE FINAL INT VALUE Public int value () { Return Value; } } l Examples of using Coin: Public class cointest { Public static void main (String [] args) { For (COIN C: coin.values ()) { System.out.println (C ": / T" C.Value () "¢ / t" color (c)); } } PRIVATE ENUM COINCOLOR { Copper, Nickel, Silver } Private static coincolor color (coin c) { Switch (c) { Case Penny: Return Coincolor.copper; Case nickel: Return coincolor.nickel; Case DIME: Case quarter: Return coincolor.silver; DEFAULT: Throw new assertionerror ("Unknown Coin:" C); } } 6, VARARGS (1) problem l Writing a method with any quantity parameters must use arrays l Creating and initializing arrays are troublesome things l If it is not better by the compiler? l is the same as the basic usage of Printf. (2) Use Java.Text.MessageFormat example Object [] arguments = { New Integer (7), New Date (), "a disturbance in the force" } String result = messageformat.format "At {1, time} on {1, date}, there WAS {2} on planet" "{0, NUMBER, INTEGER}.", Arguments; (3) Examples of using varargs String result = messageformat.format At {1, Time} on {1, date}, there is {2} on planet " "{0, Number, INTEGER}.", 7, New Date (), "a disturbance in the force"); l Format method's VARARGS declaration is as follows: Public Static String Format (String Pattern, Object ... arguments l Parameter type is Object [] l The caller does not need to use VARARGS syntax. 7, static import (1) Examples of the class export constant Public class physics { PUBLIC STATIC FINAL DOUBLE AVOGADROS_NUMBER = 6.02214199E23; Public Static Final Double Boltzmann_Constant = 1.3806503E-23; Public Static Final Double Electron_Mass = 9.10938188E-31; } l The client needs to use a qualification to access constants: Double Molecules = Physics.avogAdros_Number * Moles; (2) Avoid defined error methods // "Constant Interface" Antipattern - Do Not Use! Public interface physics { PUBLIC STATIC FINAL DOUBLE AVOGADROS_NUMBER = 6.02214199E23; Public Static Final Double Boltzmann_Constant = 1.3806503E-23; Public Static Final Double Electron_Mass = 9.10938188E-31; } Public class guacamole imports physics { Public static void main (String [] args) { Double Moles = ...; Double Molecules = AvogAdros_Number * Moles; ... } l Existence: Ø Abuse interface: not used to define types Ø Implement detail pollution export API Ø Make customer programs chaos Ø Creating a long-term commitment Ø If the compiler let us avoid the limit name is not better? (3) Solution: Static Import l Import of similar packages l Imported static members l You can also import all l Examples of static Import: Import static org.iso.physics. *; Public class guacamole { Public static void main (String [] args) { Double Molecules = AvogAdros_Number * Moles; ... } } (4) Example of the introduction method (Math) l alternative X = math.cos (math.pi * theta); to make: X = COS (Math.pi * Theta); (5) work together with ENUM Import static gov.treas.coin. *; Class myclass { Public static void main (String [] args) { Int twoBITS = 2 * quarter.value (); ... } } 8, metadata (Annotations) (1) problem l Many APIs require a considerable number of template files, such as the JAX-RPC web service requires pair of interfaces and implementations. l If you can look at the code, make the tool to generate a sample file not better? l Many APIs need additional files to maintain, such as Bean needs BeanInfo class files. l If you can look at the code, can the tool be able to generate these additional files not better? (2) Examples of JAX-RPC Web services Public interface coffeeorderif extends java.rmi.remote { Public coffee [] getpricelist () Throws java.rmi.remoteexception; Public String ORDERCOFEE (String Name, int Quantity) Throws java.rmi.remoteexception; } Public Class CoffeeOrderImpl Implements CoffeeOrderif { Public coffee [] getpricelist () { ... } Public String ORDERCOFEE (String Name, Int Quantity) { ... } } (3) Examples of using Annotations Import javax.xml.rpc. *; Public class coffeeorder { @Remote public coffee [] getpricelist () { ... } @Remote Public String ORDERCOFFEE (String Name, INT Quantity) { ... } }