Home >Java >javaTutorial >Systematic explanation of new features of JDK from versions 1.5 to 1.9 for easy comparison

Systematic explanation of new features of JDK from versions 1.5 to 1.9 for easy comparison

php是最好的语言
php是最好的语言Original
2018-07-30 15:08:172611browse

When learning the basics of Java, I summarized the new features of jdk from 1.5 to 1.9. Their uses are listed below for easy comparison. Each version is different. You can choose according to your needs. Well, I hope it can help everyone. apache php mysql

New features of jdk1.5:

1. Generic
ArrayList list=new ArrayList( )------>ArrayListc0f559cc8d56b43654fcbe4aa9df7b4alist=new ArrayListc0f559cc8d56b43654fcbe4aa9df7b4a();
2 Automatic boxing/unboxing
nt i=list.get(0).parseInt(); -------->int i=list.get(0); No explicit conversion is required between the original type and the corresponding packaging class
3 for-each
i=0;i10fb3fb41d43009e1a28cee631ea4cc1for(int i:a){......}
4 static import
Math.sqrt();---- ----------->sqrt();
5 Variable length parameters
int sum(int ...intlist) has any number of parameters, treat it as an array
New features of jdk1.6:
1. Enhanced for loop statement
Integer[] numbers = computeNumbers();
for (int i=0; i 9ac6c8e001fdc8edc6bdc14d0a34b44e {
return b.compareTo(a);
});
3. Functional interface
How Lambda expressions are types in java What is represented in the system? Each lambda expression corresponds to a type, usually an interface type. "Functional interface" refers to an interface that only contains one abstract method. Every lambda expression of this type will be matched to this abstract method. Because default methods are not considered abstract methods, you can also add default methods to your functional interface.
4. Method and constructor references
Java 8 allows you to use the :: keyword to pass method or constructor references. The above code shows how to reference a static method. We can also reference the method of an object:
converter = something::startsWith;
String converted = converter.convert("Java");
System.out.println(converted);
5. Lambda scope
In lambda Accessing the outer scope in expressions is similar to the way in older versions of anonymous objects. You can directly access outer local variables marked final, or instance fields and static variables.
6. Accessing local variables
You can directly access outer local variables in lambda expressions:
7. Accessing object fields and static variables
The difference from local variables is that the instance inside lambda Fields and static variables are both readable and writable. This behavior is consistent with anonymous objects:
8. Default method of accessing the interface
JDK 1.8 API contains many built-in functional interfaces, such as Comparator or Runnable interfaces that are commonly used in old Java. These interfaces The @FunctionalInterface annotation has been added so that it can be used on lambdas.
Java 8 API also provides many new functional interfaces to make work more convenient. Some interfaces are from the Google Guava library. Even if you are familiar with these, it is still necessary to see how these can be extended. Used on lambda.

JDK1.9 new features

java 7 was released in 2011, Java 8 was released in 2014, and java9 was released on September 21, 2017. You may have heard about Java 9's module system, but there are many other updates in this new version. Here are nine exciting new features coming with Java 9.

1. Java platform-level module system

The defining feature of Java 9 is a brand new module system. As code bases get larger, the chances of creating complex, convoluted "spaghetti code" increase exponentially. At this time, you have to face two basic problems: it is difficult to truly encapsulate the code, and the system does not have a clear concept of the dependencies between different parts (that is, JAR files). Every public class can be accessed by any other public class on the classpath, which can lead to inadvertent use of APIs that are not intended to be publicly accessible. In addition, there are problems with the classpath itself: how do you know that all the required JARs are already there, or if there are duplicate entries? The module system solves both problems.

Modular JAR files contain an additional module descriptor. In this module descriptor, dependencies on other modules are expressed through "requires". In addition, the "exports" statement controls which packages can be accessed by other modules. All packages that are not exported are encapsulated in modules by default. The following is an example of a module descriptor, present in the "module-info.java" file:

module
blog {
  
exports
com.pluralsight.blog;
 
  
requires
cms;
}

We can display the module as follows:

Please Note that both modules contain encapsulated packages since they are not exported (visualized with an orange shield). No one uses classes from these packages by accident. The Java platform itself is also modularized using its own module system. By encapsulating the JDK's internal classes, the platform is more secure and continuous improvement is easier.

When starting a modular application, the JVM will verify that all modules are available based on the `requires` statement - a big step forward from the fragile classpath. Modules allow you to better enforce structural encapsulation of your application and make dependencies explicit. You can learn more about the working of modules in Java 9 in this course.

2. Linking

当你使用具有显式依赖关系的模块和模块化的 JDK 时,新的可能性出现了。你的应用程序模块现在将声明其对其他应用程序模块的依赖以及对其所使用的 JDK 模块的依赖。为什么不使用这些信息创建一个最小的运行时环境,其中只包含运行应用程序所需的那些模块呢? 这可以通过 Java 9 中的新的 jlink 工具实现。你可以创建针对应用程序进行优化的最小运行时映像而不需要使用完全加载 JDK 安装版本。

3. JShell : 交互式 Java REPL

许多语言已经具有交互式编程环境,Java 现在加入了这个俱乐部。您可以从控制台启动 jshell ,并直接启动输入和执行 Java 代码。 jshell 的即时反馈使它成为探索 API 和尝试语言特性的好工具。

测试一个 Java 正则表达式是一个很好的说明 jshell 如何使您的生活更轻松的例子。 交互式 shell 还可以提供良好的教学环境以及提高生产力,您可以在此了解更多信息。在教人们如何编写 Java 的过程中,不再需要解释 “public static void main(String [] args)” 这句废话。

4. 改进的 Javadoc

有时一些小事情可以带来很大的不同。你是否就像我一样在一直使用 Google 来查找正确的 Javadoc 页面呢? 这不再需要了。Javadoc 现在支持在 API 文档中的进行搜索。另外,Javadoc 的输出现在符合兼容 HTML5 标准。此外,你会注意到,每个 Javadoc 页面都包含有关 JDK 模块类或接口来源的信息。

5. 集合工厂方法

通常,您希望在代码中创建一个集合(例如,List 或 Set ),并直接用一些元素填充它。 实例化集合,几个 “add” 调用,使得代码重复。 Java 9,添加了几种集合工厂方法:

Set<Integer>
ints = Set.of(
1
,
2
,
3
);
List<String>
strings = List.of(
"first"
,
"second"
);

除了更短和更好阅读之外,这些方法也可以避免您选择特定的集合实现。 事实上,从工厂方法返回已放入数个元素的集合实现是高度优化的。这是可能的,因为它们是不可变的:在创建后,继续添加元素到这些集合会导致 “UnsupportedOperationException” 。

6. 改进的 Stream API

长期以来,Stream API 都是 Java 标准库最好的改进之一。通过这套 API 可以在集合上建立用于转换的申明管道。在 Java 9 中它会变得更好。Stream 接口中添加了 4 个新的方法:dropWhile, takeWhile, ofNullable。还有个 iterate 方法的新重载方法,可以让你提供一个 Predicate (判断条件)来指定什么时候结束迭代:

IntStream.iterate(
1
,
i -> i <
100
,
i -> i +
1
).forEach(System.out::println);

第二个参数是一个 Lambda,它会在当前 IntStream 中的元素到达 100 的时候返回 true。因此这个简单的示例是向控制台打印 1 到 99。

除了对 Stream 本身的扩展,Optional 和 Stream 之间的结合也得到了改进。现在可以通过 Optional 的新方法 `stram` 将一个 Optional 对象转换为一个(可能是空的) Stream 对象:

Stream<Integer>
s = Optional.of(
1
).stream();

在组合复杂的 Stream 管道时,将 Optional 转换为 Stream 非常有用。

7. 私有接口方法

Java 8 为我们带来了接口的默认方法。 接口现在也可以包含行为,而不仅仅是方法签名。 但是,如果在接口上有几个默认方法,代码几乎相同,会发生什么情况? 通常,您将重构这些方法,调用一个可复用的私有方法。 但默认方法不能是私有的。 将复用代码创建为一个默认方法不是一个解决方案,因为该辅助方法会成为公共API的一部分。 使用 Java 9,您可以向接口添加私有辅助方法来解决此问题:

public
interface
 
MyInterface
{
 
    
void
normalInterfaceMethod();
 
    
default
void
 
interfaceMethodWithDefault()
{  init(); }
 
    
default
void
 
anotherDefaultMethod()
{ init(); }
 
    
//
This method is not part of the public API exposed by MyInterface
    
private
void
 
init()
{ System.out.println(
"Initializing"
);
}
}

8. HTTP/2

Java 9 中有新的方式来处理 HTTP 调用。这个迟到的特性用于代替老旧的 `HttpURLConnection` API,并提供对 WebSocket 和 HTTP/2 的支持。注意:新的 HttpClient API 在 Java 9 中以所谓的孵化器模块交付。也就是说,这套 API 不能保证 100% 完成。不过你可以在 Java 9 中开始使用这套 API:

HttpClient
client = HttpClient.newHttpClient();
 
HttpRequest
req =
   
HttpRequest.newBuilder(URI.create(
"http://www.google.com"
))
              
.header(
"User-Agent"
,
"Java"
)
              
.GET()
              
.build();
 
 
HttpResponse<String>
resp = client.send(req, HttpResponse.BodyHandler.asString());

HttpResponsef7e83be87db5cd2d9a8a0b8117b38cd4 resp = client.send(req, HttpResponse.BodyHandler.asString());
除了这个简单的请求/响应模型之外,HttpClient 还提供了新的 API 来处理 HTTP/2 的特性,比如流和服务端推送。

9. 多版本兼容 JAR

我们最后要来着重介绍的这个特性对于库的维护者而言是个特别好的消息。当一个新版本的 Java 出现的时候,你的库用户要花费数年时间才会切换到这个新的版本。这就意味着库得去向后兼容你想要支持的最老的 Java 版本 (许多情况下就是 Java 6 或者 7)。这实际上意味着未来的很长一段时间,你都不能在库中运用 Java 9 所提供的新特性。幸运的是,多版本兼容 JAR 功能能让你创建仅在特定版本的 Java 环境中运行库程序时选择使用的 class 版本:

multirelease.jar
├──
META-INF
│  
└── versions
│      
└──
9
│          
└── multirelease
│              
└── Helper.
class
├──
multirelease
    
├──
Helper.
class
    
└──
Main.
class

在上述场景中, multirelease.jar 可以在 Java 9 中使用, 不过 Helper 这个类使用的不是顶层的 multirelease.Helper 这个 class, 而是处在“META-INF/versions/9”下面的这个。这是特别为 Java 9 准备的 class 版本,可以运用 Java 9 所提供的特性和库。同时,在早期的 Java 诸版本中使用这个 JAR 也是能运行的,因为较老版本的 Java 只会看到顶层的这个 Helper 类。

end:写的有点长,内容也比较多,可能也掺杂很多废话,希望多多谅解哈,大家多多鼓励,我会持续更新更多优质的文章,分享使我快乐!

相关文章:

JDK 1.5之Generics

相关视频:

极客学院Java8新特性视频教程

The above is the detailed content of Systematic explanation of new features of JDK from versions 1.5 to 1.9 for easy comparison. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn