New Features of java1.5

Source: Internet
Author: User
Tags comparable

One important topic of "JDK1.5" is to simplify development by adding some features, including generics, for-each loops, automatic package installation/unpacking, enumeration, and variable parameters, static import. Using these features helps us write code that is clearer, lean, and secure.

I. First, I would like to briefly introduce various features and their usage.

1. Generic (Generic)
C ++ can specify the element type of the set through the template technology, while Java has never had the corresponding function before 1.5. An object of any type can be put in a set. When we take objects from the set, we have to forcibly convert them. Tigers introduce generics, which allow you to specify the element types in the set, so that you can get the benefit of checking strong types at compile time.


One important topic of "JDK1.5" is to simplify development by adding some features, including generics, for-each loops, automatic package installation/unpacking, enumeration, and variable parameters, static import. Using these features helps us write code that is clearer, lean, and secure.

I. First, I would like to briefly introduce various features and their usage.

1. Generic (Generic)
C ++ can specify the element type of the set through the template technology, while Java has never had the corresponding function before 1.5. An object of any type can be put in a set. When we take objects from the set, we have to forcibly convert them. Tigers introduce generics, which allow you to specify the element types in the set, so that you can get the benefit of checking strong types at compile time.

1 Collection <String> c = new ArrayList ();
2 c. add (new Date ());

The compiler will give an error:

Add (java. lang. String) in java. util. Collection <java. lang. String> cannot be applied to (java. util. Date)

2. For-Each loop
The For-Each loop must be added to simplify the traversal of the set. Suppose we want to traverse a set to process the elements. The typical code is:

[Java]
Void processAll (Collection c ){
For (Iterator I = c. iterator (); I. hasNext ();){
MyClass myObject = (MyClass) I. next ();
MyObject. process ();
}

Void processAll (Collection c ){
For (Iterator I = c. iterator (); I. hasNext ();){
MyClass myObject = (MyClass) I. next ();
MyObject. process ();
}
}

With the For-Each loop, we can rewrite the code:

[Java]
Void processAll (Collection <MyClass> c ){
For (MyClass myObject: c ){
MyObject. process ();
}
}

Void processAll (Collection <MyClass> c ){
For (MyClass myObject: c ){
MyObject. process ();
}
}

This code is much clearer than above and avoids forced type conversion.

3. Autoboxing/unboxing)
Automatic package installation/unpacking greatly facilitates the use of basic data and their packaging.
Automatic package installation: the basic type is automatically converted to the packaging class. (int> Integer)
Automatic package Splitting: the package type is automatically converted to the basic type. (Integer> int)

Before JDK1.5, we always worried that the set cannot store basic types. Now the automatic conversion mechanism solves our problem.

[Java]
Int a = 3;
Collection c = new ArrayList ();
C. add (a); // It is automatically converted to Integer.
Integer B = new Integer (2 );
C. add (B + 2 );

Int a = 3;
Collection c = new ArrayList ();
C. add (a); // It is automatically converted to Integer.
Integer B = new Integer (2 );
C. add (B + 2 );

Here, Integer is automatically converted to int for addition, and then int is converted to Integer again.


4. enumeration (Enums)
JDK1.5 adds a brand new type of "class"-Enumeration type. Therefore, JDK1.5 introduces a new keyword enmu. We can define an enumeration type in this way.

[Java]
Public enum Color
{
Red,
White,
Blue
}

Public enum Color
{
Red,
White,
Blue
}

Then we can use Color myColor = Color. Red.
The enumeration type also provides two useful static methods: values () and valueOf (). We can easily use them, for example

1 for (Color c: Color. values ())
2 System. out. println (c );

5. variable parameters (Varargs)
Variable parameters allow programmers to declare a method that accepts variable numbers of parameters. Note: variable parameters must be the last parameter in the function declaration. Suppose we want to write a simple method to print some objects,

Util. write (obj1 );
Util. write (obj1, obj2 );
Util. write (obj1, obj2, obj3 );
...

Before JDK1.5, we can implement it with reloads, but this requires writing a lot of overload functions, which is not very effective. If variable parameters are used, we only need one function.

1 public void write (Object... objs ){
2 for (Object obj: objs)
3 System. out. println (obj );
4}

After variable parameters are introduced, Java reflection packages are more convenient to use. For c. getMethod ("test", new Object [0]). invoke (c. newInstance (), new Object [0]). Now we can write c. getMethod ("test "). invoke (c. newInstance (), this code is much clearer than the original one.
6. Static import (Static Imports)
To use static members (methods and variables), we must provide the class that provides this method. Static import allows all static variables and static methods of the imported class to be directly visible to the current class, without having to give their class names.

Import static java. lang. Math .*;
.......

R = sin (PI * 2); // No need to write r = Math. sin (Math. PI );

However, over-using this feature will also reduce code readability to a certain extent.

Ii. Focus on generic

In the released Java1.4, many new APIs (such as Loging, regular expressions, and NIO) are added to the core code library, many APIs have been added in the latest JDK1.5 and JDK1.6 to be released, among which Generics (model) is of great significance ).

1. What is Generics?

Generics can be called parameterized types. The Compiler verifies the mechanism by which a type is transmitted to an object from the client. For example, Java. util. ArrayList, the compiler can use Generics to ensure type security.

Before learning about Generics, let's take a look at the current java Collection framework (Collection ). In j2SE1.4, The Root Interface of all sets is Collection.

[Java]
Protected void collectionsExample (){
ArrayList list = new ArrayList ();
List. add (new String ("test string "));
List. add (new Integer (9); // purposely placed here to create a runtime ClassCastException
InspectCollection (list );
}
Protected void inspectCollection (Collection aCollection ){
Iterator I = aCollection. iterator ();
While (I. hasNext ()){
String element = (String) I. next ();
}
}

Protected void collectionsExample (){
ArrayList list = new ArrayList ();
List. add (new String ("test string "));
List. add (new Integer (9); // purposely placed here to create a runtime ClassCastException
InspectCollection (list );
}
Protected void inspectCollection (Collection aCollection ){
Iterator I = aCollection. iterator ();
While (I. hasNext ()){
String element = (String) I. next ();
}
}

The preceding example contains two methods. The collectionExample method creates a simple set-type ArrayList and adds a String and an Integer object to the ArrayList. in the inspecCollection method, we iterate this ArrayList and use String for Cast. We can see that the second method has a problem. The Collection uses an Object internally. to retrieve the objects in the Collection, we need to perform Cast, the developer must use the actual type for Cast. For example, the compiler does not

In this way, we are at risk of throwing ClassCastException during code execution. We can see that the inspecCollection method has no problem during compilation, but the ClassCastException will be thrown during runtime. So we must stay away from this major runtime error.

2. Use Generics

From the exception of CassCastException in the previous chapter, we expect to be able to capture it during code compilation. Below we use the paradigm to modify the sample program in the previous chapter.

[Java]
Protected void collectionsExample (){
ArrayList <String> list = new ArrayList <String> ();
List. add (new String ("test string "));
// List. add (new Integer (9); this no longer compiles
InspectCollection (list );
}
Protected void inspectCollection (Collection <String> aCollection ){
Iterator <String> I = aCollection. iterator ();
While (I. hasNext ()){
String element = I. next ();
}
}

Protected void collectionsExample (){
ArrayList <String> list = new ArrayList <String> ();
List. add (new String ("test string "));
// List. add (new Integer (9); this no longer compiles
InspectCollection (list );
}
Protected void inspectCollection (Collection <String> aCollection ){
Iterator <String> I = aCollection. iterator ();
While (I. hasNext ()){
String element = I. next ();
}
}


From the above 2nd rows, we used the new syntax when creating the ArrayList, and added the Generics Declaration to all collections in JDK1.5. Example:


[Java]
Public class ArrayList <E> extends actlist <E> {
// Details omitted...
Public void add (E element ){
// Details omitted
}
Public Iterator <E> iterator (){
// Details omitted
}
}

Public class ArrayList <E> extends actlist <E> {
// Details omitted...
Public void add (E element ){
// Details omitted
}
Public Iterator <E> iterator (){
// Details omitted
}
}


This E is a type variable and does not define specific types. It is only a type placeholder when defining ArrayList, in Example 2, when we define an ArrayList instance, we use String to bind it to E. When we use the add (E element) method to add an object to ArrayList, public void add (String element); because all methods in ArrayList use String to replace E, whether it is a method parameter or a return value. Now let's look at the fourth line in Example 2, and the compilation will reflect the compilation error.

Therefore, the main purpose of adding Generics in java is to increase type security.

Through the simple example above, we can see the advantages of using Generics:

· 1. Collection is type-safe when the type does not change.

· 2. The internal type conversion is superior to the external manual shape.

· 3. Make the Java interface stronger, because it adds the type.

· 4. type Matching errors can be captured at the compilation stage, rather than during code runtime.

Variable of constrained type

Although many classes are designed to Generics, type variables can be limited.

Public class C1 <T extends Number> {}
Public class C2 <T extends Person & Comparable> {}

The first T variable must inherit the Number, and the second T must inherit the Person and implement the Comparable

3. Generics Method

Like the Generics class, methods and constructors can also have type parameters. The return values of method parameters can all have type parameters for Generics.

// Example 4

1 public <T extends Comparable> T max (T t1, T t2 ){
2 if (t1.compareTo (t2)> 0)
3 return t1;
4 else return t2;
5}

Here, the parameter type of the max method is a single T type, while the T type inherits Comparable. The parameters and return values of max have the same superclass. The following Example 5 shows the constraints of the max method.

// Example 5

1 Integer iresult = max (new Integer (100), new Integer (200 ));
2 String sresult = max ("AA", "BB ");
3 Number nresult = max (new Integer (100), "AAA"); // does not compile

In Example 5 1st, the parameters are all Integer, so the return value is also Integer. Note that the return value is not modeled.

In Example 5 2nd, the parameters are both strings, so the returned value is also String. Note that the returned value is not modeled. The same method is called.

The following compilation errors are generated in line 5 of Example 5:

Example. java: 10: incompatible types
Found: java. lang. Object & java. io. Serializable & java. lang. Comparable <?>
Required: java. lang. Number
Number nresult = max (new Integer (100), "AAA ");

This error occurs because the compiler cannot determine the type of the returned value, because both String and Integer have the same super-Class Object. Note that even if we fix the third line, this line of code still reports an error while running, because different objects are compared.

3. wildcard (Wildcards)

Check whether the following two lines of code are valid:
List <String> ls = new ArrayList <String> (); // 1
List <Object> lo = ls; // 2
The first line is okay. The key lies in the second line of code. Most people will think that "a String List is naturally a List of objects". Therefore, there is no problem with the 2nd lines.

Okay, then let's look at the following code:
Lo. add (new Object (); // 3
String s = ls. get (0); // 4: Try to assign an Object to a String!
It can be seen that through the alias lo, we can perform data operations (especially inserting an Object) on the ls, a String list, so that ls not only contains the String Object! This is not allowed by the Java compiler! During compilation, the 2nd line reports a compilation error.

Generally, if Foo is a sub-type (subclass or sub-interface) of Bar and G is a generic declaration, G <Foo> is not a sub-type of G <Bar>.

Assume that all elements in a set are to be output. The following are written in the old version and the new version (JDK 1.5:

Void printCollection (Collection c ){
Iterator I = c. iterator ();
For (k = 0; k <c. size (); k ++ ){
System. out. println (I. next ());
}}

Void printCollection (Collection <Object> c ){
For (Object e: c ){
System. out. println (e );
}}

The problem is that the new version is not as useful as the old version. because the old version uses various types of sets as parameters, the new version can only use Collection <Object>. as we can see in the previous section, Collection <Object> is not a super type (parent type) of other sets ).

The super type of all sets should be written: Collection <?>, Read as: collection of unknown (unknown set), which is a set. Its element type can match any type. Therefore, this type is called "wildcard type ".

Correct implementation of the above Old Version code can be written as follows:
Void printCollection (Collection <?> C ){
For (Object e: c ){
System. out. println (e );
}}

In this case, you can use any type of set to call this method. note that the method body still reads the element from c and assigns it to the Object. This is correct. Therefore, no matter what set of type arguments are, its elements are all objects. however, adding an object to it is insecure:

Collection <?> C = new ArrayList <String> ();
C. add (new Object (); // compilation Error

Because we do not know what the element type of c is, we cannot add an object to it. the add () method accepts a parameter of Type E, and E is the same as the element type of the set. what is the real parameter of the type? It indicates "unknown type". The parameter passed to add must be a child type of this "unknown type. unfortunately, since the type is unknown, its subtype cannot be determined, so nothing can be used as its parameter. the only exception is null, because null is a member of all types .www.2cto.com

On the other hand, if a List <?>, We can call the get () method and use the elements returned by it. although the returned element type is "unknown type", it is always an object. Therefore, the element returned by get () is assigned to an Object-type variable, or it is safe to pass the parameter to an acceptable Object.

 

Author: centralperk
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.