Java10 新特性
var关键字
局部变量的类型推断 var关键字:这个新功能将为Java增加一些语法糖 - 简化它并改善开发者体验。新的语法将减少与编写Java相关的冗长度,同时保持对静态类型安全性的承诺。
使用场景
- 局部变量初始化
- for循环内部索引变量
- 传统的for循环声明变量
使用限制
- 方法参数
- 全局变量
- 构造函数参数
- 方法返回类型
- 字段
- 捕获表达式(或任何其他类型的变量声明)
/**
* 输出:
* [hello,world!, 1, 1.01]
*/
public static void varKeyWord() {
// 这里最好带上泛型,否则list就什么都可以装了
var list = new ArrayList<>();
list.add("hello,world!");
list.add(1);
list.add(1.01);
System.out.println(list);
}
新增ByteArrayOutputStream
String toString(Charset): 重载 toString(),通过使用指定的字符集解码字节,将缓冲区的内容转换为字符串。
List、Map、Set新增API
/**
* 按照其迭代顺序返回一个不可修改的列表、映射或包含给定集合的元素的集合。
*/
public static void collectionNewAPI() {
var list = new ArrayList<String>();
list.add("hello");
list.add("world");
// copyOf返回的集合为不可变,不能增删元素
var newCopyList = List.copyOf(list);
// 这里add方法会抛出异常:java.lang.UnsupportedOperationException
// newCopyList.add("zdk");
System.out.println(newCopyList);
}
Properties新增API
/**
* 新增int入参的构造方法和重载的replace方法
*/
public static void propertiesNewAPI() {
// 新增int参数的构造函数,初始化大小,默认为8
var properties = new Properties(8);
properties.setProperty("host", "localhost");
// 只有当前值为localhost时才会替换,替换成功返回true
properties.replace("host", "localhost", "baidu.com");
System.out.println(properties);
}
Collectors收集器新增API
- toUnmodifiableList():
- toUnmodifiableSet():
- toUnmodifiableMap(Function, Function):
-
toUnmodifiableMap(Function, Function, BinaryOperator):
这四个新方法都返回 Collectors ,将输入元素聚集到适当的不可修改的集合中。
/**
* 输出:
* [hello, world]
*/
public static void collectorsNewAPI() {
var list = new ArrayList<String>();
list.add("hello");
list.add("world");
var unmodifiableList = list.stream().collect(Collectors.toUnmodifiableList());
// 不可修改的list,这里add/remove操作不会抛出异常,但add/remove不会生效
unmodifiableList.add("hello2");
System.out.println(unmodifiableList);
}