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?
-
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 allocatedintarrays will be initialized to all elements zero. -
I won't return
nullbecauseintis a primitive type. It will return the defaultintvalue, which is0.There is no way of knowing if any element has been set, short of keeping a separate boolean array.
Click Upvote : If it were an array of a custom class/enum object, would it return null if that item/index wasn't set?Nikhil Chelliah : @Click Upvote: Yes. -
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
nullfor any element not specifically assigned. -
In Java, only reference variables are initialized to null. Primitives are guaranteed to return appropriate default values. For ints, this value is 0.
-
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).
0 comments:
Post a Comment