Java 10 最明显的新特性是局部变量类型推导。
把与Java 7的写法比较下。
// Java 10
var list = new ArrayList<String>();
// Java 7
ArrayList<String> list = new ArrayList<>();
下面把与Java 8、java 5的写法都比较下,回顾一下Java的演化。
import java.util.*;
public class Java10Demo {
public static void main(String[] args) {
var demo = new Java10Demo();
demo.demoJEP286();
}
void demoJEP286() {
demoJava10();
demoJava8();
demoJava5();
}
void demoJava10() {
var list = new ArrayList<Person>() {{
add(new Person("yang", Sex.MALE));
add(new Person("gao", Sex.MALE));
add(new Person("feng", Sex.FEMALE));
}};
list.stream().filter(p -> p.sex == Sex.MALE).forEach(System.out::println);
}
void demoJava8() {
List<Person> list = new ArrayList<>() {{
add(new Person("yang", Sex.MALE));
add(new Person("gao", Sex.MALE));
add(new Person("feng", Sex.FEMALE));
}};
list.stream().filter(p -> p.sex == Sex.MALE).forEach(System.out::println);
}
void demoJava5() {
List<Person> list = new ArrayList<Person>();
list.add(new Person("yang", Sex.MALE));
list.add(new Person("gao", Sex.MALE));
list.add(new Person("feng", Sex.FEMALE));
for (Person person : list) {
if (person.sex == Sex.MALE) {
System.out.println(person);
}
}
}
}
enum Sex {
MALE, FEMALE
}
class Person {
String name;
Sex sex;
public Person(String name, Sex sex) {
this.name = name;
this.sex = sex;
}
public String toString() {
return "Person(" + name + ", " + sex + ")";
}
}