Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 197
  • Last Modified:

arrays

Its told that arrays hold similar data?
but when declare array for object we store different datatype like Int,String,Float why this ?
0
queryelango
Asked:
queryelango
1 Solution
 
Ravindra76Commented:

In that case arrays hold similar set of objects which may contain different data types. So the array definition meaning was not chagned. If You treat each object as a item , then arrays hold similar
set of items. But these items may or may not contain different  data types.
0
 
Jim CakalicSenior Developer/ArchitectCommented:
In Java, every class extends Object. The primitive types (byte, short, int, long, float, double, char) are not objects.

When you declare an array to hold one of these types, the compiler enforces the type-safety of the array by only allowing values of the primitive type to be stored in array elements.

When you declare an array to hold some kind of object, say String, the compiler will likewise enforce type-safety by only allowing object instances of type String or its subclasses (assuming one could subclass String) to be stored in array elements. Since every Java class extends Object, you can see that declaring an array to hold Objects means that the array can reasonably store instances of any Java class.

This same principle is in effect with the Java collection classes. Several of these, like Vector, actually use an array as the storage for the collection elements. Collection methods take or return Object instances. This is actually one area in which many have criticized Java because the creation of a type-safe collection takes considerably more effort than the use of templates in C++.

Best regards,
Jim Cakalic
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now