0

What is the equivalent of this without using instanceof? Maybe something more simple while using true, false or else statements?

public static void p (Object...ar)
{
        for (int i=0; i < ar.length; i++)
        {
                if (ar[i] instanceof int[])
                {
Something
  • 21
  • 4
  • Why do you need an alternative? – Eric May 09 '13 at 19:15
  • So I can better understand instanceof. – Something May 09 '13 at 19:16
  • RTTI is usually considered a "code smell". Tough there are particular cases where I can understand its use, I'd rather take a polymorphc approach. There's not much to `instanceof` actually, the docs explain it pretty well: *The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.* – Fritz May 09 '13 at 19:20
  • 2
    There really isn't something lower level than `instanceof`; there are only higher-level things and entirely different approaches to the same problem. – Louis Wasserman May 09 '13 at 19:23
  • 1
    @LouisWasserman There's the Class method `isInstance` which isn't really higher level or entirely different. – Jonathan Drapeau May 09 '13 at 19:39
  • I'm kind of new at Java. I was looking for something more simple while using true, false or else statements? – Something May 09 '13 at 19:42
  • 1
    You have the three basic elements you need to check a type, an input (`ar[i]`), a type reference (`int[]`) and an operator that does the check (`instanceof`). What sould be simpler than that for you?. – Fritz May 09 '13 at 19:47
  • I am trying to use true, false, or else operators instead of instanceof – Something May 09 '13 at 19:50
  • None of `true`, `false`, or `else` are operators. They're constants and keywords. – Eric May 09 '13 at 20:15

7 Answers7

4

For primitive arrays you can, instead of:

if (ar[i] instanceof int[])

Use:

if (ar[i].getClass() == int[].class)



Note: The above code works fine for arrays of primitive types. Please be aware, though, that instanceof also checks if the object in the left-part is a subtype of the class in the right-part, while == does not.
For objects, the equivalent to (myInstance instanceof MyClass[]) (checks for subtyping) is:

(   MyClass[].class.isAssignableFrom(  myInstance.getClass()  )   )
acdcjunior
  • 114,460
  • 30
  • 289
  • 276
  • 1
    One thing to note: this has the downside (or possibly upside, if this is error which *should* throw, but usually not) that if `ar[i]` is null, this will throw `NullPointerException`. – hyde May 09 '13 at 19:59
  • 1
    Note that in general `a instanceof A` does _not_ imply `a.getClass() == A.class` – Eric May 09 '13 at 20:11
1

You could use:

(getClass().isArray())

and checking if integer array:

 ar.getClass().toString().equals("class [I")

updated:

if(ar.getClass().isArray()) {
        if(ar[i].getClass() == int[].class)
            ....
        else if(ar[i].getClass() == String[].class)
            ....
}
Hamid
  • 1,829
  • 4
  • 17
  • 30
1

Another option would be to just assume it is an int[], and catch the resulting exception if it is not:

public static void p (Object...ar)
{
    for (int i=0; i < ar.length; i++)
    {
        int[] i_arr;
        try {
            i_arr = (int[]) ar[i];
        } catch (ClassCastException e) {
            continue;
        }
        //...
Eric
  • 87,154
  • 48
  • 211
  • 332
  • 3
    you are using exceptions as flow control, something that should be avoided – Francisco Spaeth May 09 '13 at 19:21
  • 1
    -1 for using exceptions as flow control, especially when simple alternatives exist. – user949300 May 09 '13 at 19:22
  • Something more simple than this? While using true, false, or else? – Something May 09 '13 at 19:23
  • 1
    @JavaMentor: Am I? Is this any different to trying to open a file, and skipping it if it doesn't exist? That throws an exception too. Are exceptions not at some level for flow control? Otherwise, they're be error codes. – Eric May 09 '13 at 19:23
  • No, exceptions should present a situation that isn't expected. Otherwise you will have just `Go-To`s within your code. You can find more about this topic [here](http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html) – Francisco Spaeth May 09 '13 at 19:29
  • 2
    I'm not sure I completely agree with that. At some level you expect it, else you'd never catch it. Having said that, in the context of java, [CheckDontCatch](http://c2.com/cgi/wiki?CheckDontCatch) indicates this is probably a bad idea. – Eric May 09 '13 at 19:36
  • I'm kind of new at Java. I was looking for something more simple while using true, false or else statements? – Something May 09 '13 at 19:40
  • 1
    @JavaMentor: Well, you can't use `instance of` per the OP so he is doing it an alternative way. –  May 09 '13 at 20:40
  • wouldn't it be solved using `ar[i].getClass() == int[].class` in a condition? – Francisco Spaeth May 10 '13 at 05:33
0

Generally, inheritance and polymorphism is a better solution to your problem. Rather than check what kind of object you are dealing with, have several classes inherit from a generic class, and call the shared methods.

Chris Chambers
  • 1,337
  • 20
  • 37
0

Check out java.lang.Class, which has a method isAssignableFrom(Class<?> cls)

For your specific example with arrays, it also has isArray() and getComponentType()

user949300
  • 14,622
  • 6
  • 30
  • 61
0
Class<?> intArrayCls = int[].class;

...

if (intArrayCls.isInstance(ar[i])) {

Would do the trick too.

JavaDoc of isInstance. It is a little more flexible as it doesn't just test equality like the accepted answer.

Jonathan Drapeau
  • 2,578
  • 2
  • 24
  • 32
0

use isAssignableFrom

public static void test(Object... args) {
    for (int i = 0; i < args.length; i++) {
       if (args[i].getClass().isAssignableFrom(int[].class)) {
        System.out.println("true");
       } else {
            System.out.println("false");
       }
    }
}

you can use isAssignableFrom in a dynamic way too, see this post to know the difference between instanceof and isAssignableFrom What is the difference between instanceof and Class.isAssignableFrom(...)?

Community
  • 1
  • 1
Kurohige
  • 323
  • 2
  • 10