Reputation: 267077
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?
Upvotes: 5
Views: 19806
Reputation: 1028
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...
Upvotes: 0
Reputation: 61526
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).
Upvotes: 0
Reputation: 11764
In Java, only reference variables are initialized to null. Primitives are guaranteed to return appropriate default values. For ints, this value is 0.
Upvotes: 2
Reputation: 339816
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.
Upvotes: 11
Reputation: 234484
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.
Upvotes: 3
Reputation: 399863
No.
Your array elements are only big enough to hold int
s, 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.
Upvotes: 1