| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Can an array of primitive types be casted to an array of object reference?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Can an array of primitive types be casted to an array of object reference i.e., Object[] c = new long[4]?You can have Object c = new long[4]; //case 1 Object[] c1 = new Long[4]; //case 2 but you can not have Object[] c = new long[4]; //case 3
When you create an array of type primitive and the elements of it are primitives.
eg. An array is an Object, a reference to an array can be converted to a reference of type Object. Object c1 = new long[4]; Object c2 = new Long[4]; A reference of an array of type reference can cast to a reference of an array of type Object, because any reference object is sublcass of Object. For example, Long is-a Object, an instance of array of type Long can implicitly convert to an array of type Object: Object[] c = new Long[4]; A reference of an array of type primitive can not be cast to a reference to an array of type Object. Because the elements of an array of type primitive are primitives and cannot be upcasted to Object. Also, you can't convert or cast an array of primitive to an array of different primitive. They are two different types and the compiler is complaining: "Incompatible arg type". The automatic widening or narrowing does not apply to array types as if it works for primitive types.
|