0

I have a list of nodes. This nodes are a data class I defined by myself. Each node has a data field of the type Object. Now I want to find the node in a list of nodes that has the parameter object in the data field. I wrote this method, because I wanted to first compare if the two objects (the parameter and the object in the data field) are of the same type:

public Node getnNodeByData(Object obj) {
    for (Node node : nodes) {
        if (node.getData() instanceof obj.getClass()) {

        }
    }
}

Unfortunately this condition does not work:

Incompatible operand types boolean and Class<capture#1-of ? extends Graph>

I don't really know why this is a problem. How can I make this working?

2 Answers2

4

No, you need to use Class.isInstance(Object). The instanceof keyword does not expect an object of type Class, but only the name of the class directly -- but Class.isInstance is basically analogous.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
3

No, that is not possible like that. You should use isAssignableFrom() or isInstance(). The difference between the two methods is that isInstance(null) will return false and isAssignableFrom(null) will give true.


[object] instanceof [class]

should be translated to this:

[class].class.isAssignableFrom(object.getClass());

Example:

Integer i = 4;
boolean b = i instanceof Number;
boolean k = Number.class.isAssignableFrom(i.getClass());

b and k are equivalent.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287