章
目
录
Java的instanceof运算符(也称为类型比较运算符)用于测试指定对象是否是指定类型(类、子类或接口)的实例。
instanceof返回–
- true – 如果变量是指定类、其父类或实现指定接口或其父接口的实例
- false – 如果变量不是类的实例或实现接口,或者变量为null。
HashMap map = new HashMap();
assertTrue( map instanceof Map );
assertTrue( map instanceof AbstractMap );
assertFalse( map instanceof List );
map = null;
assertFalse( map instanceof Map );
1.instanceof运算符语法
运算符instanceof
将变量测试为指定类型。变量写在运算符的左侧,类型写在运算符的右侧。
boolean value = variable instanceof ClassType;
//or
if(variable instanceof ClassType) {
//perform some action
}
2.instanceof操作符不需要显式的null检查
在Java中,null是一种类型,因此我们在使用instanceof运算符时不需要检查NullPointerException。instanceof在内部为我们做这件事。
if(map != null && map instanceof Map) {
//some action
}
在前面的示例中,我们不需要进行显式的空检查。表达式的正确写法是:
if(map instanceof Map) { //null检查是隐式的
//some action
}
3. 将instanceof与数组一起使用
在 Java 中,数组也被视为对象并具有关联的字段和方法。因此我们也可以对数组使用instanceof运算符。
原始数组是对象和自类型的实例。例如 int[] 是Object和int[]的类型。两个比较都返回 true。
int[] intArr = new int[0];
Assertions.assertTrue(intArr instanceof Object);
Assertions.assertTrue(intArr instanceof int[]);
对象数组是Object类型的、Object[]类型的、classtype类型的数组以及父类类型的数组。例如,Integer[]是Object、Object[]、Integer[]和Number[](因为Integer是Number的子类)类型的。
Integer[] integerArr = new Integer[0];
Assertions.assertTrue(integerArr instanceof Object);
Assertions.assertTrue(integerArr instanceof Object[]);
Assertions.assertTrue(integerArr instanceof Integer[]);
Assertions.assertTrue(integerArr instanceof Number[]);
4. 何时使用?
使用instanceof运算符的一个现实示例是将变量类型转换为另一种类型。instanceof运算符有助于避免运行时出现ClassCastException。
考虑以下示例,我们尝试将列表类型转换为LinkedList类,其中原始变量的类型为ArrayList。它将抛出ClassCastException。
//强制转换错误
List<String> list = new ArrayList<>();
LinkedList<String> linkedList = (LinkedList) list; //ClassCastException
为了正确地转换变量,我们可以使用instanceof运算符。它不会导致ClassCastException。
List<String> list = new ArrayList<>();
if(list instanceof LinkedList) {
LinkedList<String> linkedList = (LinkedList) list;
//other actions
} else if(list instanceof ArrayList) {
ArrayList<String> arrayList = (ArrayList) list;
//other actions
}
自Java 14起,instanceof运算符支持模式匹配。我们可以更简洁地重写上面的表达式:
List<String> list = new ArrayList<>();
if(list instanceof LinkedList linkedList) {// 自动转换为linkedList变量
//这里可以直接用linkedlist变量
} else if(list instanceof ArrayList arrayList) {// 自动转换为arrayList变量
//这里可以接用arraylist 变量
}
文章目录 前言 第1章 Java语言基础 第2章 流程控制语句 第3章 面向对象编程 第4章 Java 字符 […]