Reputation:
I want to write to a variable only if there isn't anything already there. Here is my code so far.
if (inv[0] == null) {
inv[0]=map.getTileId(tileX-1, tileY-1, 0);
}
It gives me this error:
java.lang.Error: Unresolved compilation problem:
The operator == is undefined for the argument type(s) int, null
Upvotes: 5
Views: 22362
Reputation: 20081
The error is because inv
is an array of int
, not the object wrapper Integer
. Your array comes initialized for you anyway. If you wrote
int[] inv = new int[5];
you will have an array of 5 zeroes.
You should initialize your array yourself using some value that you know is invalid (e.g. if you had an array of ages, a negative value would be invalid). Check for the invalid value and if it's there, replace it.
Upvotes: 0
Reputation: 61520
primitive types can't be compared to null.
You can test if the number if > 0 to see if a value exists:
if(inv[0] <= 0)
{
inv[0]=map.getTileId(tileX-1, tileY-1, 0);
}
Upvotes: -1
Reputation: 108967
You could try something like this
Integer[] inv = new Integer[10];
inv[0] = 1;
inv[1] = 2;
....
if(inv[3] == null)
{
inv[3] = getSomeValue();
}
Upvotes: 0
Reputation: 4843
I'm assuming from error message, that inv[]
is array of int
, and int
in java is not an object, so it cannot have null
value.. You have to compare it with 0
(default value on each index of empty int array)..
Upvotes: 2
Reputation: 46876
Well... int
is a primitive type. That can't be null.
You can check the size of the array:
int[] arr = new int[10]; System.out.println( arr.size() );
The plain arrays are indexed from 0 to their size - 1, and no value can be missing.
So in your code, you are asking whether the first member of type int
is null
, which can't happen - either it's a number or it will cause ArrayOutOfBoundsException
.
If you want to have a "sparse array" similar to what PHP or JavaScript, you need a Map
:
Map<Integer, Integer> map = new HashMap();
map.put( 1, 324 );
if( map.get( 2 ) == null ) ...
Upvotes: 0
Reputation: 1502056
I'm assuming inv
is an int[]
.
There's no such concept as a value "existing" or not in an array. For example:
int[] x = new int[5];
has exactly the same contents as:
int[] x = new int[5];
x[3] = 0;
Now if you used an Integer[]
you could use a null value to indicate "unpopulated"... is that what you want?
Arrays are always filled with the default value for the element type to start with - which is null
in the case of reference types such as Integer
.
Upvotes: 5
Reputation: 1074959
I take it that inv
is an int[]
. You can't compare an int
to null
, null
only applies to reference types, not primitives. You have to either assign it some kind of flag value instead (0
being popular, and the value it will have by default when you create the array), or make inv
an Integer[]
instead (Integer
being a reference type, it is null
-able).
Upvotes: 2