[英]How to check what the data type is being used?
I have an assignment in which one of the methods of class creates a tree node of generic type T.我有一个任务,其中 class 的方法之一创建了一个通用类型 T 的树节点。
For any TreeNode object treeNode
,对于任何 TreeNode object
treeNode
,
treeNode.getData() instanceof LinkedList
will return true
if the dataItem
is an instance of LinkedList.如果
dataItem
是 LinkedList 的实例,将返回true
。 Same goes for CircularArray. CircularArray 也是如此。
To test if an object reference is an instace of a specific class there is the infix operatorinstanceof
.要测试 object 引用是否是特定 class 的实例,有中缀运算符
instanceof
。 You can use that in an if-else-statement to handle the three different cases.您可以在 if-else-statement 中使用它来处理三种不同的情况。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.