学习Java之day30
1. Java 9 的新特性
//
@Test
public void test1() {
try {
URL url = new URL("http://www.atguigu.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
//java9特性五:钻石操作符的升级
@Test
public void test2() {
//钻石操作符与匿名内部类在java 8中不能共存。在java9可以。
Comparator<Object> com = new Comparator<>() {
@Override
public int compare(Object o1, Object o2) {
return 0;
}
};
//jdk7中的新特性:类型推断
ArrayList<String> list = new ArrayList<>();
}
//java9 特性六:try操作的升级
public static void main(String[] args) {
//java 8之前的资源关闭的操作
// InputStreamReader reader = null;
// try {
// reader = new InputStreamReader(System.in);
// char[] cbuf = new char[20];
// int len;
// if((len = reader.read(cbuf) )!= -1){
// String str = new String(cbuf,0,len);
// System.out.println(str);
// }
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// if(reader != null){
// try {
// reader.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//
// }
// }
//java 8中资源关闭操作: Java 8 中,可以实现资源的自动关闭
//要求自动关闭的资源的实例化必须放在try的一对小括号中
// try(InputStreamReader reader = new InputStreamReader(System.in)){
// char[] cbuf = new char[20];
// int len;
// if((len = reader.read(cbuf) )!= -1){
// String str = new String(cbuf,0,len);
// System.out.println(str);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//java9中资源关闭操作:需要自动关闭的资源的实例化可以放在try的一对小括号外。
//此时的资源属性是常量,声明为final的,不可修改
InputStreamReader reader = new InputStreamReader(System.in);
try (reader) {
char[] cbuf = new char[20];
int len;
if((len = reader.read(cbuf) )!= -1){
String str = new String(cbuf,0,len);
System.out.println(str);
}
// reader = null;
} catch (IOException e) {
e.printStackTrace();
}
}
//java8中的写法:
@Test
public void test1() {
List<String> namesList = new ArrayList<>();
namesList.add("Joe");
namesList.add("Bob");
namesList.add("Bill");
//返回的namesList是一个只读的集合
namesList = Collections.unmodifiableList(namesList);
namesList.add("Tom");
System.out.println(namesList);
}
@Test
public void test2() {
List<String> list = Collections.unmodifiableList(Arrays.asList("a", "b", "c"));
Set<String> set = Collections.unmodifiableSet(new HashSet<>(Arrays.asList("a", "b", "c")));
// 如下操作不适用于jdk 8 及之前版本,适用于jdk 9
Map<String, Integer> map = Collections.unmodifiableMap(new HashMap<>() {
{
put("a", 1);
put("b", 2);
put("c", 3);
}
});
map.forEach((k, v) -> System.out.println(k + ":" + v));
}
@Test
public void test3() {
//此时得到的集合list也是一个只读集合。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
//报异常
list.add(6);
}
//java9新特性八:集合工厂方法:创建只读集合
@Test
public void test4() {
List<Integer> list1 = List.of(1, 2, 3, 4, 5);
//不能添加
// list1.add(6);
System.out.println(list1);
Set<Integer> set1 = Set.of(23, 3, 54, 65, 43, 76, 87, 34, 46);
//不能添加
// set1.add(4);
System.out.println(set1);
Map<String, Integer> map1 =