java - Is there No Point to use instanceof with primitive types array? -


this somehow same asking: is there subclass / superclass primitive types?

(because ((object) (new string[6])) instanceof object[] true, string extends object.)

for instance, of int[], only ((object) (new int[3])) instanceof int[] true, among in java?

if so,

((object) (new int[3])) instanceof int[] 

is identical to

((object) (new int[3])).getclass() == int[].class 

and prefer latter one, should faster, doesn't have check every type/class inheritances.

it difficult understand asking, think asking whether using getclass() better using instanceof array types.

from perspective of readability, instanceof better:

   object obj = new int[3];     if (obj instanceof int[]) {        int[] array = (int[]) obj;    }     if (foo.getclass() == int[].class) {        int[] array = (int[]) obj;    } 

clearly, first form more readable.

from performance perspective, cannot see why 2 versions could not identical. in instanceof case, int[] type has no subtypes, , therefore can compiled equivalent or potentially faster than getclass() version.

the way sure faster write decent microbenchmark , run on platforms interested in. , note liable different performance results different versions of java

however, suspect performance difference small make difference application. unless already have concrete profiling results point bottleneck ... wasting time.


this somehow same asking: there subclass / superclass primitive types?

no. not equivalent asking @ all. java array types not primitive types. reference types.

it related question of whether there subtype relationship between array types. or more accurate, boils down whether can cast 1 array type different array type.

and answer depends on base type; see jls 5.5.1. reference type casting. if base types (different) primitive types, answer no. if base types reference types, if can cast 1 base type (bc1) other (bc2) cast involving array types (bc1[] bc2[]) legal.

so means instanceof , getclass() tests give same answer array-of-primitive types, not array types.


in fact, arguably mistake in original java language design allow any casting between different array types. leads anomalies such this:

    object[] = new string[1];     a[0] = new object();  // throws arraystoreexception !!! 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -