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?
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.
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...
Related
I have numbers[x][y] and int pm2 = 0;. Is there a way to pass on this Mult-Array onto public static boolean checkNumber(int[] list, int num)? <- the parameters has to be used this way.
I invoked checkNumber(numbers[x][y], pm2);
I need to use the checkNumber method to check if a number has already been entered and returns true if the number is present and false if number is absent.
I am allowed to use multiple methods thought so I did have an idea of doing numbers[x][0] , numbers[x][1] etc, etc and invoking them into multiple checkNumber() methods. I was just wondering if there's a shorter way.
You have single dimensional array as parameter.
So you have to pass one at a time probably in loop.
I was just wondering if there's a shorter way.
No there isn't. The Java language doesn't support any kind of array "slicing", and you can't subvert the type system to allow you to refer use an array with a different type to what it really has.
You need to implement your idea of iterating the int[] component array of the int[][], passing each one to checkNumber(int[], int). Something like this:
for (int[] subarray : numbers) {
checkNumbers(subarray, pm2);
}
I am studying for the OCA Programmer I Oracle Certification and hence I am reviewing all the tricky things tht might be on the exam.
One is this one:
int [] zero = new int[0];
Such an array declared as having 0 in the constructor what is going to actually do in the heap? creating a reference to what?
I have already tried to see whether it gives null or not and it does not. (zero != null) passes the test.
Do you have any idea? Thanks in advance.
Zero length array is still an array, and memory will be allocated to this array.
Array implements Object. Object is a class with methods a fields.
Size is also additional field in memory that indicates the size of array.
Additional info for tracing the reference to the object by the garbage collection is also needed.
As a result memory allocation is needed for all of this.
More interesting question when this array can be usefull, read this stackoverflow question.
what is going to actually do in the heap?
A zero-length int array.
creating a reference to what?
A reference to the zero-length int array.
I have already tried to see whether it gives null or not and it does not
Why should it?
Arrays in Java are objects. For instance it has "length" variable. and also the related data. Therefore even if you create a 0 size array only the data part will be zero in size. The other parts of the array object will be still there.
Hi all when writing an array list implementation, I understand it is important to set Item(x) to null when it is removed (instead of simply quantity -= 1) so as to prevent memory leaks.
However, if my array list is a primitive int array list (backed by a int[]), does it make sense to set it to 0?
Similary, for an array list of primitive chars (backed by a char[]), when RemoveRange() is called, does it make sense to fill that range with \u0000? Or is it totally fine simply to update the length and pointers without modifying the backing array?
Is an array of ints filled with zeros possibly less memory-occupying than an equal length array filled with integer values because the runtime could make optimizations ?
Is an array of ints filled with zeros possibly less memory-occupying than an equal length array filled with integer values?
Assuming in both cases we're dealing with an int[] - no. Two arrays of the same type and the same length will always occupy the same amount of memory.
There's no need to overwrite your "now empty" array elements with 0. It wouldn't do any harm (beyond a tiny performance benefit), and may even make things simpler when debugging, but you don't need to.
... when writing an array list implementation, I understand it is important to set Item(x) to null when it is removed (instead of simply quantity -= 1) so as to prevent memory leaks.
This isn't true. Setting variables to null is not something that is always necessary and not doing so does not mean that you have a memory leak.
However, if my array list is a primitive int array list, does it make sense to set it to 0?
No, for primitives it doesn't matter at all, 0 or \u0000 (for a char) is just a value like any other value. It doesn't take up less space.
No, it's not necessary to do so with primitive types (i.e. set them to 0) since the only reason "slots" are explicitly nulled out are to prevent fake references to them thereby screwing around with garbage collection.
You can't have an ArrayList<int> nor any other container class with primitives. Regarding plain arrays, see Jon Skeets answer.
No, you need to nullify the object slot in the array to prevent the leak. If the object is still referenced by your array then it can't be GC'd - so the leak you refer to.
Primitives on the other hand are allocated on the stack anyway, not the heap, so aren't GC'd anyway. Primitives that are instance vars of classes are stored as fields of the relevant object and cleaned up when the object is GC'd.
Additionally, the JLS indicates that the size of a primitive is VM-specific but most (all?) VMs currently support 4byte ints. See the JLS for more info:
Primitives and references always occupy the same amount of space.
I was wondering about the implementation of length of a Java Array. I know that using arrayName.length gives us the number of elements in the array, but was wondering if this is a method / function or it is just a data member of Array?
I guess it must be a data member as we do not use parenthesis() when invoking it. But if it is a data member how/when is the value of this length assigned/computed?
According to the Java Language Specification (specifically ยง10.7 Array Members) it is a field:
The public final field length, which contains the number of components of the array (length may be positive or zero).
Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.
The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:
[...] arrays have a third header field, for the array size.
You're correct, length is a data member, not a method.
From the Arrays tutorial:
The length of an array is established when the array is created. After creation, its length is fixed.
If you have an array of a known type or is a subclass of Object[] you can cast the array first.
Object array = new ????[n];
Object[] array2 = (Object[]) array;
System.out.println(array2.length);
or
Object array = new char[n];
char[] array2 = (char[]) array;
System.out.println(array2.length);
However if you have no idea what type of array it is you can use Array.getLength(Object);
System.out.println(Array.getLength(new boolean[4]);
System.out.println(Array.getLength(new int[5]);
System.out.println(Array.getLength(new String[6]);
Yes, it should be a field. And I think this value is assigned when you create your array (you have to choose the length of array while creating, for example: int[] a = new int[5];).
I believe its just a property as you access it as a property.
String[] s = new String[]{"abc","def","ghi"}
System.out.println(s.length)
returns 3
if it was a method then you would call s.length() right?
From the JLS:
The array's length is available as a
final instance variable length
And:
Once an array object is created, its
length never changes. To make an array
variable refer to an array of
different length, a reference to a
different array must be assigned to
the variable.
And arrays are implemented in the JVM. You may want to look at the VM Spec for more info.
It is a public final field for the array type. You can refer to the document below:
http://java.sun.com/docs/books/jls/third_edition/html/arrays.html#10.7
Every array in java is considered as an object. The public final length is the data member which contains the number of components of the array (length may be positive or zero)
Java arrays, like C++ arrays, have the fixed length that after initializing it, you cannot change it. But, like class template vector - vector <T> - in C++ you can use Java class ArrayList that has many more utilities than Java arrays have.
I have a fairly expensive array calculation (SpectralResponse) which I like to keep to a minimum. I figured the best way is to store them and bring it back up when same array is needed again in the future. The decision is made using BasicParameters.
So right now, I use a LinkedList of object for the arrays of SpectralResponse, and another LinkedList for the BasicParameter. And the BasicParameters has a isParamsEqualTo(BasicParameters) method to compare the parameter set.
LinkedList<SpectralResponse> responses
LinkedList<BasicParameters> fitParams
LinkedList<Integer> responseNumbers
So to look up, I just go through the list of BasicParameters, check for match, if matched, return the SpectralResponse. If no match, then calculate the SpectralResponse.
Here's is the for loop I used to lookup.
size: LinkedList size, limited to a reasonable value
responseNumber: just another variable to distinguish the SpectralResponse.
for ( i = size-1; i > 0 ; i--) {
if (responseNumbers.get(i) == responseNum)
{
tempFit = fitParams.get(i);
if (tempFit.isParamsEqualTo(fit))
{
return responses.get(i);
}
}
}
But somehow, doing it this way no only take out lots of memory, it's actually slower than just calculating SpectralResponse straight. Much slower.
So it is my implementation that's wrong, or I was mistaken that precalculating and lookup is faster?
You are accessing a LinkedList by index, this is the worst possible way to access it ;)
You should use ArrayList instead, or use iterators for all your lists.
Possibly you should merge the three objects into one, and keep them in a map with responseNum as key.
Hope this helps!
You probably should use an array type (an actual array, like Vector, ArrayList), not Linked lists. Linked lists is best for stack or queue operation, not indexing (since you have to traverse it from one end). Vector is a auto resizing array, wich has less overhead in accessing inexes.
The get(i) methods of LinkedList require that to fetch each item it has to go further and further along the list. Consider using an ArrayList, the iterator() method, or just an array.
The second line, 'if (responseNumbers.get(i) == responseNum)' will also be inefficient as the responseNumbers.get(i) is an Integer, and has to be unboxed to an int (Java 5 onwards does this automatically; your code would not compile on Java 1.4 or earlier if responseNum is declared as an an int). See this for more information on boxing.
To remove this unboxing overhead, use an IntList from the apache primitives library. This library contains collections that store the underlying objects (ints in your case) as a primitive array (e.g. int[]) instead of an Object array. This means no boxing is required as the IntList's methods return primitive types, not Integers.