• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Testing Array of Primitive Vs Array of Object

 
Alec Lee
Ranch Hand
Posts: 569
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an array whose element type I do not know until runtime. That is, it could be an array to object, array to array, array to primitive. I need a simple method to loop thru the array and test if it contains an element convertible to a certain numeric value. The element include numeric primitives, their wrappers, BigDecimal/BigInteger, any instance of java.lang.Number.

I would use recursion to loop thru the whole array since it may be an array of array. But the problem is how can i test if the array elements are primitive type. Here is my code that failed at line 6 because of casting primitive to Object[]



Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The java.lang.Class class has a number of useful methods you're not using. There's isArray() (a vastly better substitute for checking if there's a bracket in the class name!), there's getComponentType() (which tells you the data type of the elements of an array) and there's isPrimitive() which tells you if a class represents a primitive type. So to check if something is a primitive array, you'd do

 
Henry Wong
author
Marshal
Pie
Posts: 21437
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alec Lee wrote:But the problem is how can i test if the array elements are primitive type. Here is my code that failed at line 6 because of casting primitive to Object[]


Can you simply test if the array is of the primative type that you want? Instead of testing the elements? ... Or test if the array type is *not* an object array type?

Henry
 
Rob Spoor
Sheriff
Pie
Posts: 20611
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest is right. And to get access to the elements you can use java.lang.reflect.Array.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic