This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Java in General and the fly likes Testing Array of Primitive Vs Array of Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Testing Array of Primitive Vs Array of Object" Watch "Testing Array of Primitive Vs Array of Object" New topic
Author

Testing Array of Primitive Vs Array of Object

Alec Lee
Ranch Hand

Joined: Jan 28, 2004
Posts: 569
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

Joined: Jul 08, 2003
Posts: 24183
    
  34

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



[Jess in Action][AskingGoodQuestions]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18765
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19685
    
  20

Ernest is right. And to get access to the elements you can use java.lang.reflect.Array.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Testing Array of Primitive Vs Array of Object