An important theme of "JDK1.5" (the development of the Tiger) is to simplify development by adding features such as generics, For-each loops, automatic packaging/unpacking, enumerations, variable parameters, static import. Using these features helps us write more clear, lean, and secure code.
Here's a quick introduction to these new features.
1. Generic type (Generic)
C + + Template technology allows you to specify the element type of a collection, and Java has no corresponding functionality until 1.5. A set can put any type of object, and we also have to force the type conversion to take objects from the collection accordingly. The Tigers introduce generics, which allow you to specify the type of elements in a collection, so that you get the benefit of strong typing for type checking at compile time.
Collection C = new ArrayList ();
C.add (New Date ());
The compiler will give an error:
Add (java.lang.String) in java.util.Collection cannot is applied to (java.util.Date)
2.for-each Cycle
For-each loops are added to simplify the traversal of the set. Let's say we're going to walk through a set and do some processing on the elements. The typical code is:
void processAll(Collection c){
for(Iterator i=c.iterator(); i.hasNext();){
MyClass myObject = (MyClass)i.next();
myObject.process();
}
}
Using the For-each loop, we can rewrite the code to:
void processAll(Collection c){
for (MyClass myObject :c)
myObject.process();
}
This code is much clearer than the above and avoids coercion of type conversions.
3. Automatic packaging/unpacking (autoboxing/unboxing)
Automatic packing/Unpacking greatly facilitates the use of basic types of data and their packaging.
Automatic package: The basic type is automatically converted into a wrapper class. (int >> Integer)
Automatic unpacking: The wrapper class is automatically converted to the base type. (Integer >> int)
Before JDK1.5, we were always brooding on the inability of the collection to store the basic types, and now the automated conversion mechanism solves our problem.
int a = 3;
Collection c = new ArrayList();
c.add(a);//自动转换成Integer.
Integer b = new Integer(2);
c.add(b + 2);
Here the integer is automatically converted to int for addition operations, and then int is converted to integer again.
4. Enumeration (Enums)
JDK1.5 has added a completely new type of "class"-enum type. For this JDK1.5 introduced a new keyword ENMU. We can define an enumeration type like this.
public enum Color
{
Red,
White,
Blue
}
You can then use the Color MyColor = color.red.
The enumeration type also provides two useful static method values () and valueof (). We can use them very conveniently, for example
for (Color c : Color.values())
System.out.println(c);