如何检查正在使用的数据类型?
How to check what the data type is being used?
我有一个作业,其中 class 的方法之一创建了泛型 T 的树节点。
对于任何 TreeNode 对象 treeNode
,
treeNode.getData() instanceof LinkedList
如果 dataItem
是 LinkedList 的实例, 将 return true
。 CircularArray 也是如此。
要测试对象引用是否是特定 class 的实例,可以使用中缀运算符 instanceof
。您可以在 if-else 语句中使用它来处理三种不同的情况。
Object data = treeNode.getData();
if (data instanceof LinkedList) {
LinkedList list = (LinkedList)data;
// do stuff ...
} else if (data instanceof CircularArray) {
CircularArray array = (CircularArray)data;
} else {
// error state - throw excpetion or handel this case someother way
}
我有一个作业,其中 class 的方法之一创建了泛型 T 的树节点。
对于任何 TreeNode 对象 treeNode
,
treeNode.getData() instanceof LinkedList
如果 dataItem
是 LinkedList 的实例, 将 return true
。 CircularArray 也是如此。
要测试对象引用是否是特定 class 的实例,可以使用中缀运算符 instanceof
。您可以在 if-else 语句中使用它来处理三种不同的情况。
Object data = treeNode.getData();
if (data instanceof LinkedList) {
LinkedList list = (LinkedList)data;
// do stuff ...
} else if (data instanceof CircularArray) {
CircularArray array = (CircularArray)data;
} else {
// error state - throw excpetion or handel this case someother way
}