Java5 new Features

Source: Internet
Author: User
Tags deprecated sin

An important theme of "Jdk1.5/java5" is to simplify development by adding some features.

These features include generics, For-each loops, automatic unpacking/unpacking, enumeration, mutable parameters, static import , annotations .

Using these features helps us to write more clear, lean, and secure code.

1. Generics (Generic)
C + + uses template technology to specify the element type of the collection, and Java does not have a corresponding function until 1.5. A collection can put objects of any type, and we also have to force the type conversion when we take objects from the collection accordingly. The tiger introduced generics, which allow you to specify the types of elements in the collection, so you can get the benefits of type checking at compile time for strong types.

collection<string> C = new ArrayList (); C.add (new Date ());

The compiler will give you an error:

Add (java.lang.String) in java.util.collection<java.lang.string> cannot is applied to (java.util.Date)

2.for-each Cycle
For-each loops are added to simplify the traversal of the collection. Let's say we're going through a collection to 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<myclass> c) {for (MyClass myobject:c) {myobject.process (); } }

This code is much clearer than the above and avoids coercion of type conversions.

3. Automatic Package/unpacking (autoboxing/unboxing)
Automatic unpacking/unpacking greatly facilitates the use of basic type data and their wrapper classes.
Automatic package: The basic type automatically turns into a wrapper class. (int >> Integer)
Automatic unpacking: Wrapper classes are automatically converted to basic types. (Integer >> int)

Before JDK1.5, we were always brooding over the collection's inability to store the basic types, and now the automatic conversion mechanism solves our problem.

int a = 3; Collection C = new ArrayList ();  C.add (a);//Convert to integer automatically. Integer b = new integer (2); C.add (b + 2);

Here the integer is automatically converted to int for the addition operation, and then int is converted to integer again.
4. Enumeration (Enums)
JDK1.5 adds a new type of Class-enum type. A new keyword ENMU is introduced for this JDK1.5. We can define an enumeration type like this.

public enum Color {Red, white, Blue}

You can then use this to

Color MyColor = color.red.

Enumeration types also provide two useful static methods for values () and valueof (). We can easily use them, for example

For (Color c:color.values ()) System.out.println (c);

5. Variable parameters (Varargs)
Mutable parameters enable programmers to declare a method that accepts a variable number of parameters. Note that the mutable parameter must be the last parameter in the function declaration. Let's say we're going to write an easy way to print some objects,

Util.write (OBJ1); Util.write (OBJ1,OBJ2); Util.write (OBJ1,OBJ2,OBJ3);

Before JDK1.5, we can use overloading to implement, but this need to write a lot of overloaded functions, it is not very effective. If we use mutable parameters, we just need a function.

public void Write (object ... objs) {for (object Obj:objs) System.out.println (obj);}

After the introduction of variable parameters, the Java reflection package is also more convenient to use. For

C.getmethod ("Test", new Object[0]). Invoke (C.newinstance (), new object[0]),

Now we can write that.

C.getmethod ("Test"). Invoke (C.newinstance ()),

This code is a lot clearer than it used to be.
6. Static import (passive imports)
To use static members (methods and variables) We must give the class that provides this method. Using static import allows all static and static methods of the imported class to be directly visible in the current class, using these static members without giving their class names.

import static JAVA.LANG.MATH.*;.......R = sin (PI * 2); No more write R = Math.sin (Math.PI);

However, the overuse of this feature also reduces the readability of the code to some extent.

7. Annotations (Annotations)

Annotations (also known as metadata): Provides a formalized way for us to add information to our code so that we can use it very conveniently at a later point in time.
The javase contains 3 standard annotations:
@Override indicates that the current method definition overrides the method in the superclass. If you are not careful with spelling errors, or if the method signature is not on the overridden method, the compiler will issue an incorrect hint.
@Deprecated If the programmer uses annotations as its elements, the compiler will issue a warning message.
@SuppressWarnings Incorrect compiler warning information is turned off.

Annotation application:

When we overwrite the methods in the parent class, it is best to use the @override annotation, which avoids some unknown errors, otherwise, when your method name or method signature has a problem, the program will process it as a new method, and after using this annotation, if you accidentally appear the above error, Then the compiler will give you hints to help us encode correctly.
When we use the @deprecated annotation in the method we wrote, the compiler warns us that this method is obsolete and that the style is a horizontal line in the name of the method.
@SuppressWarnings This annotation can be interpreted as a suppressed warning, when we forget to use generics, the compiler gives a warning that we don't have a type yet, and we don't want to make a specific generic type, and we don't want the compiler to give a warning. Then we can use this annotation to suppress the warning, which can be applied at the method level or at the class level.

here is the official description of Oracle Java:Enhancements in JDK 5
  • generics -this long-awaited enhancement to the type system allows atype or method to operate on objects of Variou  s types while providingcompile-time type safety. It adds compile-time type safety to thecollections Framework and eliminates the drudgery of casting. See the generics Tutorial. (JSR 14)

  • Enhanced for Loop -this New language construct eliminates the Drudgeryand error-proneness of iterators and index variables when it Erating overcollections and arrays. (JSR 201)

  • autoboxing/unboxing -this Facility eliminates the drudgery of manualconversion between primitive types (such as I NT) and wrapper types (Suchas Integer). (JSR 201)

  • typesafe Enums -this Flexible object-oriented enumerated type facilityallows you to create enumerated types with  Arbitrary methods Andfields. IT provides all the benefits of the Typesafe Enum pattern ("Effective Java," Item) without the verbosity and the Error-p Roneness. (JSR 201)

  • Varargs -this Facility eliminates the need for manually boxing upargument lists to an array when invoking Metho DS that acceptvariable-length argument lists.

  • static Import -this facility lets you avoid qualifying Static Memberswith class names without the shortcomings of The "Constant Interfaceantipattern." (JSR 201)

  • Annotations (Metadata)-this language feature lets you avoid writing boilerplate codeunder many circumstances by enabling tools to Gen Erate it fromannotations in the source code. This leads to a "declarative" programming style where the programmer says what should is done Andtools emit the code to do  It.  Also It eliminates the need formaintaining "side files" that must is kept up to date with changes Insource files. Instead The information can is maintained in Thesource file. (JSR 175)
    Note:the @Deprecated Annotation provides a-to-deprecate program elements. See how and if to deprecate APIs.

Generics papers
  • Jsr14:adding Generic Types to the Java programming Language

    • Generics Tutorial (PDF) Bracha

    • Latest JSR14 Draft specification which includes an older prototype release of Javac

    • Earlier Public Review Draft specification from Java Community Process

  • Making the future Safe for the past:adding genericity to Thejava programming Language (PDF)
    Bracha, Odersky, Stoutamire, and Wadler.      OOPSLA 98, Vancouver, October 1998. (Other formats)

  • Gj:extending the Java programming Language with Type Parameters (PDF)
    Bracha, Odersky, Stoutamire, and Wadler. A tutorial on GJ.     August 1998. (Other formats)

  • Adding generics to the Java programming Language (PDF)
    Bracha. Slides from JavaOne 2003 presentation.

  • Adding wildcards to the Java programming Language (PDF)
    Torgersen, Hansen, Ernst, Ahe, Bracha and Gafter. An ACM paper, 2004.

General Papers
    • New Language Features for Ease of development in J2SE 5.0:a conversation with Joshua Bloch

    • Forthcoming Java Programming Language Features (PDF)

Enhancements in JDK v1.4
  • Assertion Facility -assertions is Boolean expressions that the programmer believes to be true concerning the St Ate of a computer program.  For example, after sorting a list, the programmer might asserts that the list is in ascending order. Evaluating assertions at runtime to confirm their validity are one of the most powerful tools for improving code quality, a S it quickly uncovers the programmer ' s misconceptions concerning a program ' s behavior.

For more information
    • Java Language Specification


Java5 new Features

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.