Wednesday, December 19, 2007

Google Interview Questions Part 5

Here is a snippest of code, how it is possible that the code would throw ArrayIndexOutOfBoundsException ?

private static String[] list = null;

public static String[] getArray(size) {
list= new String[size];
for (int i = 0; i < size; i++) {
list[i] = "a" + i
}
return list;
}

This question is a bit tricky

5 comments:

alider said...

Hi,
access to the 'list' is not synchronized, so it's easy to imagine the situation when next thread access this method and change the 'list' (smaller size) just when the fist thread is iterating.

b0b0b0b said...

assume you have enough memory: use Integer.MAX_INT for size.

Georgi said...

I am not pretty sure, but might a size smaller than zero throw the exception, too?

Anonymous said...

It will not throw any exception. In fact, the code won't do a thing since it will not compile without a data type specified for the "size" argument in the getArray function.

Seriously, assuming they correct that glaring mistake, I agree with alider that multiple threads accessing this code could make it screw up easily.

Richard Dingwall said...
This comment has been removed by the author.

Links

 
RSS Feeds Submission Directory