本篇博文参考了以下大佬文章,感谢大佬无私分享:
目录
1、传统与模式匹配的区别:
- 传统instanceof的用法是先判断类型,然后再进行强制类型转换,比较臃肿。
- 模式匹配的instanceof将类型判断与类型转换合二为一。
共同点:在使用null 匹配instanceof 时,返回都是false(见举例1.2)
举例1.1:
@Test
public void testInstance0f(){
Object d = new Date();
//传统写法,先判断类型再强制转换:
if(d instanceof String){
String s = (String) d;
System.out.println(s.length());
}
//传统写法,先判断类型再强制转换:
if(d instanceof Date){
Date date = (Date)d;
System.out.println(date.getTime());
}
//模式匹配写法,先判断类型和强制转换一步到位:
if(d instanceof String s){
System.out.println(s.length());
}
//模式匹配写法,先判断类型和强制转换一步到位:
if(d instanceof Date date){
System.out.println(date.getTime());
}
}
举例1.2:
注意:在使用null 匹配instanceof 时,返回都是false:
@Test
public void test1() {
Object obj = new String("hello,Java14");
obj = null;//在使用null 匹配instanceof 时,返回都是false.
if (obj instanceof String ) {
String str = (String) obj;
System.out.println(str.contains("Java"));
} else {
System.out.println("非String类型");
}
if (obj instanceof String str) { //新特性:省去了强制类型转换的过程
System.out.println(str.contains("Java"));
} else {
System.out.println("非String类型");
}
}
2、模式匹配的特点:
instanceof模式匹配的模式变量有如下特征 :
模式变量是代码块的局部变量,只有模式匹配的代码块内有效,举例如下:
举例2.1:
@Test
public void test2(){
// Object target = "java";
Object target = new Date();
//此模式变量str作用域仅限于此if代码块内:
if(target instanceof String str){
System.out.println("字符串的长度为:" + str.length());
}
//此处依旧可以将模式变量定义为str,因为前面的str仅在前面的if块内有效
if(target instanceof Date str){
System.out.println("从1970年1月1日0时0分到现在总共多少ms:" + str.getTime());
}
}
举例2.2:
@Test
public void test3(){
Object target = new Date();
//因为 && 要求前面的条件必须为true, s是有效的String变量,因此可调用s.length():
if(target instanceof String s && s.length() > 6){
System.out.println("字符串长度为" + s.length());
}
//这个是错误的,因为||只要求二者之一为ture,所以当程序执行到后面的||条件时,s完全可能是无效的String变量
if(target instanceof String s && s.length()>6 || s.length() < 4){
System.out.println("字符串长度为" + s.length());
}
}
举例2.3:
注意:此案例省略了this.model.equals(other.model) 和 this.price == other.price 中的this
//举例3:
class Monitor{
private String model;
private double price;
// public boolean equals(Object o){
// if(o instanceof Monitor other){
// if(model.equals(other.model) && price == other.price){
// return true;
// }
// }
// return false;
// }
public boolean equals(Object o){
return o instanceof Monitor other && model.equals(other.model) && price == other.price;
}
}
3、模式变量的作用域易错点:
一定要注意局部变量的有效范围/作用域: