I'm confused on whether I need to do array initialization...
For this code:
private int[][][] rPos = new int[SIZE][SIZE][2];
Can I start using the array right way, like the following line?
getLocationOnScreen(rPos[i][j]); // pass an array of two integers
And, for this code:
View[][] allViews = new View[SIZE][SIZE];
I then have to make another nested loop, and initialize every View by calling their constructors like so:
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
allViews[i][j] = new View(ctor1, ctor2);
}
}
My question is, why didn't I need to do this for an integer array? And also, what did my "new" keyword do, when I typed View[][] allViews = new View[SIZE][SIZE];?
why didn't I need to do this for an integer array?
Whenever you create an array, the array elements are assigned the default value for the component type of that array. For an int, the default value is 0, so for an int[], all the elements will be initialized to 0 by default.
With reference type, however, the default value is null. So, the issue with those arrays are that, you might get potential NullPointerException, when you try to access some property or method in those array elements. Basically, with array of reference, we mean that the array elements are nothing but references to the actual objects. Initially they don't point to any object.
So, to access any property or method, you have to initialize each array elements to some instance, so as to avoid the NPE.
what did my "new" keyword do, when I typed View[][] allViews = new View[SIZE][SIZE];?
It created an array of array, of type View. The dimension being SIZE x SIZE. But since View is not a primitive type, but a reference type. The values are by default null, as already explained.
getLocationOnScreen(rPos[i][j]); // pass an array of two integers
Of course you passed an array of 2 integers. The component type of rPos[i][j] is an int[]. The default value is null for that too. But in this case, it wouldn't be null, as you have given the dimension for all of your inner array too.
If you change your array declaration to:
private int[][][] rPos = new int[SIZE][SIZE][]; // Missing last dimension
then the value of rPos[i][j] will be null.
Related
In this Trie implementation, children array elements are assigned null value individually using a for loop.
TrieNode(){
isEndOfWord = false;
for (int i = 0; i < ALPHABET_SIZE; i++)
children[i] = null;
}
However, by default, when we create an array of reference types in Java, all entries will have default value as null which is:
TrieNode[] children = new TrieNode[ALPHABET_SIZE];
The above step assigns default values of children array entries as null.
Is it required to have null assignment once again in the for loop inside that TrieNode constructor?
No it's not required - for each class variable, instance variable, or array component Java will always assign reasonable default value (like 0 for int or null for Object) - you can read more here
However notice that for local variables it's not guaranteed
The compiler will assign a reasonable default value for fields of the above types; for local variables, a default value is never assigned.
and that's why you are forced to initialize it manually
public void f() {
String s;
System.out.println(s); // will cause Error: java: variable s might not have been initialized
}
Suppose there is a class MyObject which has a MyClass() constructor and is properly implemented.
When we call that line of code will it create instances of the MyClass object or will something else happen?
Edit: apparently this question was not very well-received. I'm sorry if it's vague or something. It was simply a homework question that asks for T/F.
I meant to ask:
if we have
MyClass[][] x = new MyClass[n][n]; // where n is a number
Will it create n*n instances of MyClass objects or merely n*n null references?
It turns out that
MyClass[][] x = new MyClass[n][n]; // where n is a number
x[0][0] = new MyClass();
is different from
MyClass x = new MyClass();
Each slot in the Array would be initially null if the Array is of any object (Primitive data types would simply yield their default value). Just like String x; where x would be null, just in this case, it's an array of null values.
The Array is still the same type of objects it was created for, such a String, just all the slots are null and would need to be instantiated. eg bigArray[1] = new String("Hello!");
If you'd like the array to contain some sort of default, you'll need to fill the array.
MyObject array = new MyObject[3]; //New array that can hold three
for(int i = 0; i < array.length; i++){ //Start i at zero, while it's less than the spots in the array, and add one every time
array[i] = new MyObject(); //Set the spot to a "real" object now.
}
I'm having trouble reassigning values in an array.
public static void main(String[] {
int[] arrayOfIntegers = new int[4];
arrayOfIntegers[0] = 11;
arrayOfIntegers[1] = 12;
arrayOfIntegers[2] = 13;
arrayOfIntegers[3] = 14;
arrayOfIntegers = {11,12,15,17};
}
Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?
Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?
Because Java doesn't have destructuring assignment like some other languages do.
Your choices are:
Assign a new array to the array variable as shown by Rohit and Kayaman, but that's not what you asked. You said you wanted to assign to the elements. If you assign a new array to ArrayOfIntegers, anything else that has a reference to the old array in a different variable or member will still refer to the old array.
Use System.arraycopy, but it involves creating a temporary array:
System.arraycopy(new int[]{11,12,15,17},
0,
ArrayOfIntegers,
0,
ArrayOfIntegers.length);
System.arraycopy will copy the elements into the existing array.
You need to provide the type of array. Use this:
arrayOfIntegers = new int[] {11,12,15,17};
From JLS Section 10.6:
An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.
If you are trying to re-assign array elements in some range, you can't do that with direct assignment. Either you need to assign values at indices individually, or use the way as given by #TJCrowder in his answer.
The correct syntax is:
arrayOfIntegers = new int[]{11,12,15,17};
I wrote a function that would take variable arguments as object.
When I passed in an array of ints of size 1 eg {9}, it treated args[0] as and int array[] than an int so the valueOf did not produce 9.
But If passed in and array of 2 or more ints eg {9,11} then it treated args[0] as 9 and args[1] as 11.
Why does it behave differently.
Note it is being written for Android.
protected String[] whereArgs(Object...args) {
String[] argsStrings = new String[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] instanceof String){
argsStrings[i] = (String)args[i];
} else {
argsStrings[i] = String.valueOf(args[i]);
}
}
return argsStrings;
}
EDIT Just had a look again I was actually passing them differently in the two ints scenario, one by one and not in an array, sorry.
Why doesn't it split the method(Object...args) into an array of objects when I pass in an array of ints, like what happens with method(int...args)
So now to get the string value I have to individually cast the type of array eg. for int[], double[]
if (args[0] instanceof int[]){
argsStrings[0] = String.valueOf(((int[])args[0])[0]);
Is there a way to write it for any type of object as this causes a crash
argsStrings[0] = String.valueOf(((Object[])args[0])[0]);
java.lang.ClassCastException: int[] cannot be cast to java.lang.Object[]
If you want to pass an array and treat each item as a separate item of the 'args' parameter of your method.. you need to cast your array to an Object[]. e.g: If you pass in your array of integers like below it will do what you want.
whereArgs((Object[])(new Integer[]{1, 2}))
The reason for this is when the source is compiled var-arg methods are actually replaced by an array. all places where the method is being called is converted to an array. If you want to pass an array so that each item becomes a separate argument.. then you need to use the correct array type. in your scenario this will be Object[]. This lets the compiler know that it can leave the method call as it is (without putting the arguments inside a new object[])
Is there some hidden meaning in this code which I don't see in java? How can it be useful?
int[] a = new int[1];
than just
int a;
because from my point of view it's the same?
int a
defines a primitive int.
int[] a = new int[1];
defines an array that has space to hold 1 int.
They are two very different things. The primitive has no methods/properites on it, but an array has properties on it (length), and methods (specifically its on clone method, and all the methods of Object).
Arrays are a bit of a weird beast. They are defined in the JLS.
In practice, it would make sense to do this when you need to interact with an API that takes an array and operates on the results. It is perfectly valid to pass in a reference to an array with 0, 1, or n properties. There are probably other valid reasons to define an array with 1 element.
I can't think of any use cases where you would want to define an array with one element, just to bypass the array and get the element.
One is on the stack, one is on the heap.
One difference is that you can write a method that changes its int argument by changing arg[0]. This trick is used quite a bit in some of the code I've seen. It allows you to, for instance, return a boolean indicate success or failure and an int value that serves some other purpose. Without that trick, you'd have to return some sort of object containing the two values.
int a;
defines a variable that can hold an int
int[] a;
defines a variable that can hold an array of int
int[] a = new int[1];
does that above but also initializes it by actually creating an array (of size 1 - it can hold 1 int) and defines the variable a to hold that array, but doesn't define what's in the array.
int[] a = new int[1]{1};
does that above but also defines what's in the array: the int 1.
I suppose it does a similar thing, in that space is allocated for 1 int, but the array also defines an array. I suppose you could say these are similar:
int a = 1;
int b = a + 1;
// now b == 2
int[] a = new int[1]{1};
int b = a[0] + 1;
// now b == 2
An array of size one is not the same thing as a single integer.
Even if they carry the same information, they are different types, so you can use them in different contexts.
For example, if you have a function which performs a function on all elements of an array but you want to compute it only on one value, you should pass a int[1], because the function expects an array and wants to know how many values it should process.
All arrays in java are objects. when declaring: int x = 5; you're declaring a primitive type.
When declaring int[] x = new int[]; you're creating an object with type int[].
So int[] is actually a class.