Search code examples
javaarrayssubclassing

Subclassing Array


If you're not interested in a story, skip the first 2 paragraphs.

I was talking to a friend about arrays and why they (still) crash if you try to access an object that is out of bounds in "modern" languages like Objective C (That's my main language). So we got into a debate and I said that I could write him an Array (I named it GeniusArray) that returns null and prints out an error if you try to access something out of bounds but does not crash.

After sleeping over it I realized that if you are accessing elements that are out of bounds you have some serious errors in your code and it's maybe not bad for app to crash so you get forced to fix it. :-D

But still: I'd like to prove my point and subclass an Array and override the get() method by basically adding this one if statement that every programmer writes relatively often:

// Pseudo code...
if (index < array.count) element= array[index];

I want to do it in Java and not Objective C because that's what my friend "knows" (btw, we are both students).

To cut a long story short: I tried to subclass an Array but it doesn't seem to work. I'm get ting this:

Access restriction: The type Attribute.Array is not accessible due to restriction on required library: /System/Library/Frameworks/JavaVM.framework/Versions/1.6.0/Classes/classes.jar GeniusArray.java


Solution

  • Languages such as C, C++ and Objective-C do not check array bounds (and hence result in unpredictable behaviour if you try to access an array with an invalid index) for performance reasons.

    Java does check array bounds on every array access and you'll get an ArrayIndexOutOfBoundsException if you use an invalid index. Some people argue that because of this built-in check arrays in Java are less efficient than in other programming languages.