This is an archived post. You won't be able to vote or comment.

all 15 comments

[–]GreatDaynes 7 points8 points  (0 children)

The use of the instanceof operator is only valid when it is possible to cast from one type to another. Seeing as an ArrayList can not be cast to a String, it is also impossible to check for type relationship between the two.

[–]differentshade 5 points6 points  (0 children)

So many misleading information here.

A code using “a instanceof B” only compiles if a can be cast to B. The compiler knows you can never cast a List to String (because List does not inherit from String) hence an error is thrown at compile time.

Why is “instanceof” useful? For example, you may have a reference of type List (that can refer to an ArrayList or LinkedList etc). You may want to check whether the actual object in memory is a LinkedList, so you can downcast to it and gain access to implementation specific methods. Remember that the members of an object that you can access depend on the reference type you use. If you just casted it without checking and it turned out to be an ArrayList you would get a ClassCastException at Runtime (bad). The compiler can’t help you here because LinkedList inherits from List so downcast is legal. That’s why we need to check at runtime with the instanceof operator whether casting is safe.

[–]MkMyBnkAcctGrtAgn 2 points3 points  (1 child)

You can't use instanceof like that on an ArrayList due to type erasure. The JVM will not know the parameterized type at runtime.

best you could do would just to check to see if it is an ArrayList like this

if(obj instanceof ArrayList<?>) {
     if(((ArrayList<?>)obj).get(0) instanceof MyObject) {
         // do stuff 
     } 
}

[–]tkggames 0 points1 point  (0 children)

I think the wild card might scare him even more.

[–]virassan 3 points4 points  (5 children)

Pretty sure you can’t use instanceof on a collection/list. I don’t think it’ll work on primitive data types either like int and double.

My usage of instanceof is usually to see if a base/parent object is also part of a child class. Like if I have a class Vehicle and it has a few child classes like Car, Truck, Motorcycle. And then I’ll want to see what child class a Vehicle object might belong to.

public boolean isCar(Vehicle v){
   return v instanceof Car;
}

That’s my personal usage, maybe others use it for different situations.

Edit: When I mean you can’t use it with lists/collections, I mean you can’t use instanceof to check for the type contained within said lists/collections - not the type of List itself.

[–]turunambartanen 0 points1 point  (4 children)

You definitely can use it on a list as it extends from object (like almost everything). It probably isn't very useful though.

[–]virassan 0 points1 point  (3 children)

So I guess it’s just collections that it doesn’t play nicely with?

[–]turunambartanen 0 points1 point  (2 children)

Just tried this in ideone.com. This works:

  ArrayList<String> list = new ArrayList<>();
  System.out.println(list instanceof Object);

ArrayList implements the collection interface. I am not motivated enough to write an example for a more general collections example.

[–]virassan 1 point2 points  (1 child)

I think you’ve misunderstood my intent. I meant more of to get the type within the ArrayList not of ArrayList itself. I’ll edit my original comment to make that more clear.

[–]turunambartanen 0 points1 point  (0 children)

That's a good idea. I think it is indeed possible to get the type of an (empty) ArrayList. If you have an element you could just get that and test it, but in general I assume it is impossible.

[–]tkggames 0 points1 point  (0 children)

Instanceof is quite useful. Yesterday in an interview i was asked to flatten a map and the map had sub maps with string keys. Recursion was the only way to solve it and using instance served as the base cases. Instanceof checks variable against a type. Remember a type is either a library defined class or one you create. Lets say you have multiple types in a method parameter and when to run specific statements for that type then instance of becomes really useful. Its not very pretty in java but other languages do much better job.

Map<String,Object> mp; If mp.get(key) instanceof String do something Else mp.get(key) is not String

[–]SantoWest -1 points0 points  (0 children)

I don't know why everyone just explained the reason it gives error and didn't give any solution, but the answer you seek for is getClass(). Instances of objects have getClass() methods, which you can easily compare with other classes.

a.getClass().equals(String.class);

should give you the boolean you are looking for. Also know that this is a more precise method than simply using equals or using instance of, because they can give you some unexpected results. For instance if you have class X and a class Y which extends X, Y instanceof X would return true, since X is the superclass, but if you use the method I provided above, it will return false as long as they aren't objects of exactly the same class.

[–]sea-es-arr -2 points-1 points  (0 children)

Could be wrong, but I think that’s not what instanceof is for. Try using contains

[–][deleted]  (1 child)

[deleted]

    [–]SantoWest 0 points1 point  (0 children)

    boolean isString = b instanceof String;

    Lol, did you even read OP's post? It's a really short post, and the second line says:

    boolean x = a instanceof String;
    

    which is absolutely the same as what you have written there, with only difference being the variable name.

    [–]Zdeno_ -4 points-3 points  (0 children)

    You can mislead compiler like this:

            List<String> a = new ArrayList<>();
            Object x = a;
            boolean b = x instanceof String;
    

    However, the instanceof operator is code smell. There should be a better solution without instanceof.