Question

If I have an int array structured like this:

private int[][] map = new int[400][400];

And I try to retrieve

map[100][200]

And that element isn't initialized, will i get a compiler/runtime error or will it return null? And is there any function to check if a given element/index exists/has been set?

Was it helpful?

Solution

As your array declaration is of a primitive type you won't get any compiler or runtime errors - the default value of 0 will be returned.

If your array had been an array of Objects, then the array would hold null for any element not specifically assigned.

OTHER TIPS

I won't return null because int is a primitive type. It will return the default int value, which is 0.

There is no way of knowing if any element has been set, short of keeping a separate boolean array.

In Java, only reference variables are initialized to null. Primitives are guaranteed to return appropriate default values. For ints, this value is 0.

No.

Your array elements are only big enough to hold ints, in this case. There is no place to store the information about if the element "exists". It has been allocated, thus it exists. In Java, newly allocated int arrays will be initialized to all elements zero.

You can use checkstyle, pmd, and findbugs on your source (findbugs on the binary) and they will tell you things like this.

Unfortunately it doesn't look like they catch this particular problem (which makes sense the the array is guaranteed to have each member set to 0, null, or false).

The use of those tools can will catch instance and class members (that are not arrays) that are being used before being given a value though (similar sort of issue).

Bit of a dead topic but I found it by accident so I'm gonna place my piece of wisdom (or whatever :P). You could use Arrays.Fill to fill your array when it's created with an invalid value like -1. Then you can easily do an if x<0 to check if YOU have initialized that specific array position or not. Just an idea...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top