Object[] array = new Object[]{};
System.out.println((array instanceof Serializable));//passed
System.out.println((array instanceof Cloneable));//passed
This code compiles and runs. The output is:
true
true
However, this code doesn’t compile:
System.out.println((array instanceof Iterable));//not passed
The Eclipse compiler reports:
Incompatible conditional operand types Object[] and Iterable
I found that arrays can only be compared between interfaceSerializable and Cloneable when using operation instanceof. Can someone tell me why?
According to the JLS, Java SE 7 edition, §15.20.2 (Type Comparison Operator
instanceof):And §15.16 (Cast Expressions) states:
Finally, §5.5.1 (Reference Type Casting) states:
Therefore, Java requires that your test to see if an array type is an instance of
java.lang.Iterableresults in a compile-time error.If you want to try and make it work (always return
false) anyway, you can cast the array toObjectfirst, like so: