Java Basics (1)-Compare the new features of JDK5,JDK6,JDK7

Source: Internet
Author: User
Tags new set

JDK8 has been out for a long time, here to learn a simple summary of the JDK5,JDK6 and Jdk7 new features:
This article outlines:

I. New features of JDK5

Two. new features of Jdk6

Three. New features of Jdk7

I. New features of JDK5

First, a brief introduction to the various features and their use

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,

When we take objects from the collection accordingly, we also have to cast them into a forced type. The tiger introduced generics, which allowed the specified set

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

A, type safety

Discard list, Map, use list<t>, map<k,v> to add elements to them or use iterator<t> traversal, compile time can give you to check out the type error

B, the method parameter and the return value are added with the type

Discard list, Map, use list<t>, map<k,v>

C, no type conversions required

List<string> list=new arraylist<string> ();

String Str=list.get (i);

D, type wildcard "?"

Assuming a method of printing elements in a list<t> printlist, we want list<t> of any type T to be printed:

Code:

public void Printlist (list<?> list,printstream out) throws Ioexception{for (iterator<?> i=   List.iterator (); I.hasnext ();) {System.out. println (I.next.tostring ()); }}

What if a wildcard character? To make our parameter types too broad, we can change list<?>, iterator<?> to

list<? Extends number>, iterator<? Extends number> limit it.

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 (); }} #使用For-Eachloop, we can rewrite the code to: void Processall (collection<myclass> c) {for (MyClass myObject: c)          

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.

4. Enumeration (Enums)
JDK1.5 adds a new type of Class-enum type. For this JDK1.5 introduced a new keyword ENMU, which we can define as an enumeration type.

public enum Color{red,white,blue} #然后可以这样来使用Color mycolor = color.red. #枚举类型还提供了两个有用的静态方法values () and valueof (). We can easily use them, such as for   

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,

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   

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 C.getmethod ("test"). Invoke (C.newinstance ()), so the code is much 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 eliminates the need to give 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.

6.Annotations It's metadata in Java.

Three standard annotation predefined in A.tiger

(1). Override method Overloading

Point out that a method covers the methods of superclass when you want to overwrite the spelling of the way name does not compile

(2). Deprecated Method Obsolete

Indicates that the use of a method or element type is blocked and the subclass will not be able to overwrite it

(3). supresswarnings Compiler Warning

Turn off compile-time warnings for class, method, field, variable initialization, such as: list does not use Generic, then @suppresswarnings ("unchecked") removes compile-time warnings.

B. Custom annotation

Public @interface marked{}

C.meta-annotation

or annotation's annotation.

All four of the standard meta-annotation are defined in the Java.lang.annotaion package:
Target
Specifies which program units the defined annotation can be used on
If target is not specified, it means that the annotation can be used on any program unit
Code

@Target ({elementtype.annotation_type,            elementtype.constructor,             Elementtype.field,            Elementtype.local_variable,             Elementtype.method,             elementtype.package,            elementtype.parameter,            Elementtype.type}) Public       @interface TODO {}  

Reflection of the annotation
We found that Java.lang.Class has many methods related to annotation's reflection, such as Getannotations, isannotationpresent
We can use annotation reflection to do many things, such as customizing annotation to do model object validation
Code

@Retention (retentionpolicy.runtime)      @Target ({elementtype.field, elementtype.method})      public @ Interface Rejectempty {         /** hint title used in error message *         /String value () default "";      }          @Retention (retentionpolicy.runtime)      @Target ({elementtype.field, elementtype.method})     public @ Interface Acceptint {         int min () default integer.min_value; int max () default integer.max_value; String hint () default ""       

Use @rejectempty and @acceptint to annotate the field of our model and then use reflection to do model validation

7. New Format method (Java.util.Formatter)

Formatter.format ("Remaining account balance: $%.2f", balance);

8. New threading model and concurrency library thread Framework
Replacement of HashMap Concurrenthashmap and ArrayList copyonwritearraylist
The use of some classes in the Java.util.concurrent package when reading large concurrency will make everyone satisfied blockingqueue, callable, Executor, Semaphore ...

Two. new features of Jdk6

1. Introduced a new framework that supports scripting engines

Enhancement of 2.UI

3. Enhancements to WebService support (jax-ws2.0 and JAXB2.0)

4. A range of new security-related enhancements

5.jdbc4.0

6.Compiler API

7. General-Purpose annotations support

Three. New features of Jdk7

1. Binary literals
JDK7 start, you can finally use binary to represent integers (byte,short,int and long). The advantage of using binary literals is that it can be
The code is more easily understood. The syntax is very simple, just add 0b or 0B before the binary value

byte Nbyte = (byte) 0b0001;short Nshort = (short) 0b0010;int nInt = 0b0011;long nlong = 0b0100l;  

2. Digital literals can appear underlined

For some of the larger numbers, we don't always define the aspects, often missing or increasing the number of digits. JDK7 provides us with a solution
Scenario, the underscore can appear in the digital literal.

int a = 10_0000_0000;long B = 0xffff_ffff_ffff_ffffl;byte c = 0b0001_1000; 

Note: You can only place underscores between numbers, and the following methods are incorrect,
(1). The beginning or end of a number

(2). Before and after the decimal point

(3). ' The suffix of f ' or ' F '

(4). Can only be used as a numeric location

int err1 = _11,err2=11_;float err3=3._4,err4=3_.4; long err5=0x888_f; 

The 3.switch statement can be used as a string

private static void switchstring (String str) {switch(str) {case "one": System.err.println ("1"); Case "Both": System.out.println ("2"); break;d efault : System.out.println ("err");}}   

4. Creation of generic instances can be simplified by type inference

After you create a generic instance, you don't need to elaborate on the type, just use <> the compiler will automatically match you

#例如

map<string, list<string>> myMap = new hashmap<string, list<string>> ();

#可以简化为
map<string, list<string>> myMap = new hashmap<> ();

5. Passing non-materialized parameters (non-reifiable formal Parameters) in a Variadic method to improve compilation warnings and errors
Some parameter types, such as arraylist<number> and List<string>, are non-materialized (non-reifiable). During the compilation phase,
The compiler erases the type information.
Heap pollution refers to a variable that is pointed to another variable that is not of the same type. For example

List L = new arraylist<number>(); list<string> ls = l; Unchecked Warningl.add (0, New Integer (42)); Another unchecked warningstring s = ls.get (0); ClassCastException is thrown

Back to our topic, in Jdk7, when you define the following function

public static <T> void Addtolist (list<t> listarg, t ... elements) {for (t x:elements) {Listarg.add (x );}}

You'll get a warning

Warning: [varargs] Possible heap pollution from parameterized vararg type

Before Jdk7, when you invoke a variable parameter method that contains non-materialized parameters, you must make your own assurances that the heap
Pollution ". There is a problem, if the caller is unfamiliar with the method, he simply cannot judge. JDK7 has made improvements to this method, which is determined by the
The time of Righteousness warns

1. Add annotation @SafeVarargs2. Annotation @SuppressWarnings ({"Unchecked", "VarArgs"}) 3. Use compiler parameters –xlint: varargs;  

6.try-with-resources statements
JDK7 provides try-with-resources that automatically shuts down related resources (as long as the resource implements the Autocloseable interface, JDK7 is the absolute
This interface is implemented by most resource objects)

Static string Readfirstlinefromfile (String path) throws IOException {try (bufferedreader br = new BufferedReader (new< c2> FileReader (path)) {return br.readline ();}}  

A try statement block can also handle multiple resources at the same time, you can catch exceptions like normal try statements, there are finally statement blocks

Try (java.util.zip.ZipFile ZF = new java.util.zip.ZipFile (zipfilename); Java.io.BufferedWriter writer =  Java.nio.file.Files.newBufferedWriter (Outputfilepath, CharSet)) {}catch(...) {}finally{}    

7.Catch multiple Exception,rethrow exception improved type detection

Many times, we catch multiple exceptions, but do the same thing, such as logging, wrapping the new exception, and then Rethrow. This
, the code is less elegant, such as

Catch (IOException ex) {Logger.log (ex); throw Ex;catch (SQLException ex) {Logger.log (ex); throw ex;} 

Jdk7 allow multiple exceptions to be captured

catch (ioexception|  SQLException ex) {Logger.log (ex); throw ex;} 

Note that the exception parameter after the catch is final and cannot be copied again

When you re-throw multiple exceptions, you no longer need to define the exception type in detail, and the compiler already knows which exception you are throwing. You
Simply declare the exception you want to throw at the time of the method definition

public void call () throws Reflectiveoperationexception, IOException {try {callwithreflection (arg);} catch ( Final Exception e) {logger.trace ("Exception in Reflection", E); throw e;}}    

8.jdbc4.1 has updated two new features

1. Both Connection,resultset and statement implement the Closeable interface, all of which are tuned in the Try-with-resources statement
You can automatically close the resources.

Try (Statement stmt = con.createstatement ()) {...}

2. RowSet 1.1: Introduce the Rowsetfactory interface and Rowsetprovider class to create various row sets supported by the JDBC driver

Rowsetfactory myrowsetfactory = null; Jdbcrowset Jdbcrs = null; ResultSet rs = null; Statement stmt = null, try {myrowsetfactory = Rowsetprovider.newfactory ();//with default Rowsetfactory implementation Jdbcrs =  Myrowsetfactory.createjdbcrowset ();//Create a Jdbcrowset object, configure the database connection properties Jdbcrs.seturl ("Jdbc:myDriver:myAttribute"); Jdbcrs.setusername (username); Jdbcrs.setpassword (password); Jdbcrs.setcommand ("Select ID from TEST");
Jdbcrs.execute ();
}

The Rowsetfactory interface includes methods for creating different types of rowset
Createcachedrowset
Createfilteredrowset
Createjdbcrowset
Createjoinrowset
Createwebrowset


9. Updated the NIO2.0 file system

Java.io.File is not perfect. JDK7 provides a new set of file systems that will make you happy.
Let's talk about the seven Sins of Java.io.File:)
1. Many methods fail without throwing an exception, it is difficult to find the reason
2. Method rename running in different platforms is problematic
3. Cannot really support symbolic links
4. Unable to read more detailed properties of the file, such as permissions, owner ...
5. Metadata inefficient access to files
6. Many methods of performance are not good. For example, dealing with larger catalogs
7. Unable to recursively find the file tree, and symbolic links with loops may cause problems

Mainly include:
FileSystem provides a number of ways to get information about the current file system.
Path processing paths (files and directories), including
Create Path,paths.get (String s)
Get more information on Path GetName (), Getxx () ...
Remove redundant information for path Torealpath
Convert Path Toabsolutepath ()
Merge two path resolve ()
Create a relative path between two paths Relativeze ()
Comparison path equal () StartsWith (), Endwith ()

Files supports a variety of file operations, including
Move files,
Copy files,
Delete files,
More detailed file attributes, including file permissions, creator, modification time ...
Walking the file tree (recursively traversing the filesystem)
Watch a Directory for change (listen for file changes)

9. Asynchronous IO AIO

Overview
The JDK7 introduces asynchronous I/O. I/O programming is commonly used in two modes: Reactor and Proactor. Reactor is
Is the NIO of Java. When an event is triggered, we are notified and processed accordingly. Proactor is the AIO we are going to talk about today.
AIO for I/O operations, are asynchronous processing, when the event is complete, we will be notified.
JDK7 's AIO includes network and file operations. The two are similar, this article through a complete client/server sample to Detail
The network operation of the Brightfield Aio.
AIO provides two types of listening mechanisms for asynchronous operations. The first is by returning a future object to the event, and calling its get () waits until the operation
Complete. The second type is similar to a callback function. When an asynchronous operation is performed, a completionhandler is passed, and when the asynchronous operation ends, it is tuned
Using the Completionhandler.complete interface

Java Basics (1)-Compare the new features of JDK5,JDK6,JDK7

Related Article

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.