user744251
user744251

Reputation:

Are arrays really Objects?

See the code below -

class test {
  public static void main(String args[]){
      int[] somearray = {1, 2};
      printarray(somearray);
  }

  static void printarray(Object[] array){
      System.out.println(array[0]);
  }
}

The above code will not compile since the printarray method cannot accept primitive arrays. Or is this an auto-boxing limitation? If so, then I consider this a BIG limitation.

Upvotes: 2

Views: 104

Answers (4)

Ramón Gil Moreno
Ramón Gil Moreno

Reputation: 819

About your question title "Are arrays really Objects?": yes, they are.

About the problem you describe: an array of primitive types is not an array of objects (as an int is not a java.lang.Object).

To make your code work, you can declare your array like this:

Integer[] somearray = {1, 2};

Instead of using the primitive type int.

Note that some boxing is into effect here.

Upvotes: 4

Razib
Razib

Reputation: 11163

Arrays are Object. Actually in java world every non primitive type is Object. Because each class you create is directly or indirectly the subclass of Object (java.lang.Object).

Look the following code snippet -

int[] intArray = new int[10];
Object anObject = intArray; //valid assignment
Object[] objArray = intArray; //invalid assignment.

Here intArray is itself an Object. So it can be assigned with an Object. But intArray is not not an array of Object that is - Object[]. So we can not assign intArray to Object[].

Upvotes: 0

nafas
nafas

Reputation: 5423

think of this way:

int is NOT Object, its primitive data type

thus int[] is not the same as Object[]

if you want to keep you printarray method the same, then you should change your somearray to Integer (Object representing of integers)

e.g.

Integer[] somearray = {1, 2};
printarray(somearray);

Upvotes: 0

Maroun
Maroun

Reputation: 95958

Are arrays really Objects?

Arrays are dynamically created objects, and they serve as a container that hold a (constant) number of objects of the same type. It looks like arrays are not like any other object, and that's why they are treated differently.

Your code will compile if you fix your main signature to:

public static void main(String args[])

It'll not compile if you add printarray(somearray), because somearray is an array containing int, where printarray (that should be named printArray) is a method accepting array of Object.

There are many solutions for your problem, one of them is changing someArray to be of type Integer[].

Upvotes: 0

Related Questions