Personal summary of some new features of JAVA8

Source: Internet
Author: User
Tags api manual

At present, Java8 has released a number of versions, for the new features in the Java8 although the great God for the jdk8 of the English characteristics of the document translation, but are too official language, against a few translation I do a summary of the new characteristics of the document, To help me and you do not know Java8 new features of the Java engineers to understand it, the level is limited, there are mistakes please enlighten me.

Interface improvements (default method for interfaces):

Before Java8 the function of the interface is to standardize the class that implements the interface, in which only constants and abstract methods can be defined.

JAVA8 allows us to define a non-abstract method, which is a static method, which is defined by the default keyword, and is also known as the extension method, as shown in the code below.

1     InterfaceFormula {2 3         DoubleCalculateinta);4 5Publicdefault Doublesqrtinta) {6 7             returnMath.sqrt (a);8 9 }Ten  One}



The class that implements the formula interface simply implements the Calculate method, and the Sqrt method is implemented in the interface, so that the subclasses do not need to implement the direct invocation, the following is an anonymous implementation of the code.

  

1Formula Formula =NewFormula () {2 3 @Override4      Public DoubleCalculateinta) {5 6         returnsqrt (A * 100);7 8 }9 Ten }; One  AFormula.calculate (100);//100.0 -  -FORMULA.SQRT (16);//4.0



A number of default methods are also added in the interface of the Java8 core class library, which should be found in the API manual.

Function Interface:

Function interface is a core concept introduced in Java8, if an interface only defines the only abstract method, then this interface becomes a function interface. such as the thread interface java.lang.Runnable is a typical function interface, in the Runnable interface only public abstract void run (); method is an abstract method.

The abstract keyword is implied, just to indicate that this is a functional interface and does not necessarily need to be. and any number of default methods can be defined in the function interface, which is entirely up to the engineer's own decision.

Add a new annotation (note) @FunctionalInterface, this annotation can be placed in front of the interface, to indicate that this interface is a function interface, this annotation and @override function is similar, only to declare the use of intent, to avoid the wrong use, and will not be compiled.

Lambdas expression:

The Lambdas expression provides a cleaner and more readable code for JAVA8.

Before Java8, the creation of anonymous internal classes often makes the code less readable, following an anonymous inner class that implements a string:

1list<string> names = Arrays.aslist ("Peter", "Anna", "Mike", "Xenia");2 3Collections.sort (Names,NewComparator<string>() {4 5 @Override6      Public intCompare (String A, string b) {7 8             returnB.compareto (a);9 Ten } One  A});


This code is very unfriendly to program engineers, especially if there is a lot of this code in the program that is a disaster for people with little experience.

The creation of this anonymous class can be simplified by using the Lambdas expression:

Collections.sort (names, (string A, string b), {     return  B.compareto (a); });



Obviously this way of using lambdas expression can make code reading more good, of course, we can write the above code shorter, for the function body only one line, you can remove {} and return keyword:

  

Collections.sort (names, (string A, string b), B.compareto (a));



But it can be even shorter:

  

Collections.sort (names, (A, B), B.compareto (a));



Because the Java compiler can automatically derive the parameter types, you can no longer write the type again. Here are some lambdas expressions to help you better understand the lambdas expression.

On the left is the parameter list for the specified type, and the return code block on the right:

 

(intint b)->{return x+y;}



On the left is the argument list of the inferred type, and the return value on the right:

 

(x, y)->x+y



The left is a single-argument deduction list, and the right is the return value:

  

X->x*x



Left no parameter (official name: "Burger Arrow"), right a return value:

  

()->x



Left derivation type single parameter, no return value code block (void) on right:

  

X, {System.out.println (x);}



static method References:

  

String::valueof equivalent to X, string.valueof (x)



Non-static method references:

  

Object::tostring equivalent to X, X.tostring ()



inherited function References:

  

X::tostring equivalent to () x.tostring ()



Constructor Reference:

  

New Arraylist<> ()



Overloads are also valid for Lambdas. A lambda and a given functional interface are compatible when the "outer" match is in the form. With "outer form", I point to the input, the type of output, and the declaration check exception.

Two examples:

  

Comparator<string> C = (A, b), Integer.compare (A.length (), b.length ());



A comparator<string> compare method needs to enter two parameters and then return an int. This is consistent with the right side of the lambda, so this task is valid.

  

Runnable r = () {System.out.println ("running!");}



A runnable run method requires no parameters and no return value. This is consistent with the right side of the lambda expression, so the task is valid.

It is also important to check for exceptions (if any) in the signature of an abstract method. If the function-type interface declares an exception in its signature, lambda can only throw a check exception.

Captured and non-captured lambda expressions:

When a lambda expression accesses a non-static variable or object defined outside the body of a lambda expression, the lambda expression is called "captured." For example, the following lambda expression captures the variable x:

  int x = 5;  return y x + y;



To ensure that the lambda expression declaration is correct, the variable it captures must be "valid final". So either they need to be marked with final modifier symbols, or they are guaranteed to not change after assignment.

A non-captured lambda from performance is typically more efficient than a captured lambda.

Some features that Lambda does not provide

non-final* variable Capture-If a variable is given a new value, it will not be used in lambda. The "final" keyword is not required, but the variable must be "valid final".

  

    int count = 0; List<String> strings = Arrays.aslist ("A", "B", "C") {    count///  Error: Cannot modify the value of Count });



Exception transparency-If a detected exception may be thrown from within the lambda, the functional interface must also declare that the detection exception can be thrown. This exception is not distributed to the methods it contains.


Control flow (break, early return)-the traditional continuation method is possible by placing "return" within the lambda; To achieve. However, there is no way to break the loop or return a value from the lambda with the result of the containing method.

 

 Final boolean containssecret (iterable<string>if  (Secret.equals (s)) {  //   want to terminate the loop and return true, but not}    }); }  


Abstract classes cannot be instantiated by LAMDBA-the most common argument for doing this is to increase the difficulty of reading Lambda. Instantiating an abstract class in this manner will result in the execution of the hidden code: The method of constructing the abstract class.

The above is my other translation of the JAVA8 the summary of the document, in the summary process also found that the translation of the document has a lot of ambiguity in the language of the place, in contrast to the original understanding, but limited to my English ability is limited, only partial details of the place has been modified, If we have a better understanding and hope to communicate with you more progress. The new and optimized API sections in JAVA8 are also summarized for grooming.

Personal summary of some new features of JAVA8

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.