I understand that everything in Java is an object. But what are the advantages of Arrays being objects too? Any special significance to it?
Printable View
I understand that everything in Java is an object. But what are the advantages of Arrays being objects too? Any special significance to it?
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:
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.
Code:Class type = x.getClass();
if(type.isArray()){
Class elementType = type.getComponentType();
}
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.