PDA

Click to See Complete Forum and Search --> : Why are Arrays Object [Sort of Resolved]


onbliss
May 15th, 2003, 03:05 PM
I understand that everything in Java is an object. But what are the advantages of Arrays being objects too? Any special significance to it?

Bootking
May 15th, 2003, 03:58 PM
When an array is an object the advantage is that you can access its length property and you can use .equals(array) to compare it to another array. Consider this, for some unknown reason I am cycling through some colors in an applet.

Color[] clrs = {Color.red, Color.blue, Color.green};
for (int i=0; i<clrs.length; ++i)
{
//Do some junk
}

You can edit the array without having to edit the rest of the program to accompany it. :) :cool:

Dillinger4
May 15th, 2003, 04:51 PM
An array treated and manipulated as an object in Java not only gains the advantages that BootKing has pointed out but also given an arbitrary object x, you can find out if the object x is an array and, if so, what type of array it is.


Class type = x.getClass();

if(type.isArray()){
Class elementType = type.getComponentType();
}

CornedBee
May 17th, 2003, 05:07 AM
Being an object also allows arrays to be stored in collections like ArrayList.
And it allows them to be passed as object, as is necessary because an int[] (or other arrays of basic types) can't be cast to Object[], so the System.arraycopy method would need to be overloaded instead of accepting Object arguments.