How do I check if an array element exists? - java

I'm looking for Java's equivalent of PHP's isset();
int board[][]=new int[8][8];
...
if(isset(board[y][x]))
// Do something with board[y][x]
Does such a function exist in Java?
Edit: Sorry, what I meant is that I want to check if board[100][100] exists or not. if(board[100][100]) would result in an array out of bounds error.

In Java, int arrays are initialized to a value of zero, so you won't be able to tell if it's been not set, or if it's set to a value of 0.
If you want to check if it's set, you should use an array of Integer. If the value isn't set, it will be null.
Integer[][] board = new Integer[8][8];
...
if (board[x][y] != null) { ... }

I think a basic null check would work.
String[] myArray = {"Item1", "Item2"};
for(int x =0; x < myArray.length; x++){
if(myArray[0] != null)
{
...do something
}
}

You can create a method that checks that first the x, y is in the bounds of the array and if it is that the value is not null. I don't believe there is a built in method for array, but there are helper functions similar like .contains() for ArrayLists.

Probably better to not use int, you could use Integer if you really have to have it as an int, but generally speaking a complex object is going to be better (like a ChessPiece or something). That way you can check to see if the value == null (null means it has not been set).

if (board[x][y] != null) {
// it's not null, but that doesn't mean it's "set" either. You may want to do further checking to ensure the object or primitive data here is valid
}
Java doesn't have an equiv. to isset because knowing if something is truly set goes beyond just stuffing a value into a location.

Related

Delete value for previously assigned int field [duplicate]

Can an int be null in Java?
For example:
int data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
My goal is to write a function which returns an int. Said int is stored in the height of a node, and if the node is not present, it will be null, and I'll need to check that.
I am doing this for homework but this specific part is not part of the homework, it just helps me get through what I am doing.
Thanks for the comments, but it seems very few people have actually read what's under the code, I was asking how else I can accomplish this goal; it was easy to figure out that it doesn't work.
int can't be null, but Integer can. You need to be careful when unboxing null Integers since this can cause a lot of confusion and head scratching!
e.g. this:
int a = object.getA(); // getA returns a null Integer
will give you a NullPointerException, despite object not being null!
To follow up on your question, if you want to indicate the absence of a value, I would investigate java.util.Optional<Integer>
No. Only object references can be null, not primitives.
A great way to find out:
public static void main(String args[]) {
int i = null;
}
Try to compile.
In Java, int is a primitive type and it is not considered an object. Only objects can have a null value. So the answer to your question is no, it can't be null. But it's not that simple, because there are objects that represent most primitive types.
The class Integer represents an int value, but it can hold a null value. Depending on your check method, you could be returning an int or an Integer.
This behavior is different from some more purely object oriented languages like Ruby, where even "primitive" things like ints are considered objects.
Along with all above answer i would like to add this point too.
For primitive types,we have fixed memory size i.e for int we have 4 bytes and char we have 2 bytes. And null is used only for objects because there memory size is not fixed.
So by default we have,
int a=0;
and not
int a=null;
Same with other primitive types and hence null is only used for objects and not for primitive types.
The code won't even compile. Only an fullworthy Object can be null, like Integer. Here's a basic example to show when you can test for null:
Integer data = check(Node root);
if ( data == null ) {
// do something
} else {
// do something
}
On the other hand, if check() is declared to return int, it can never be null and the whole if-else block is then superfluous.
int data = check(Node root);
// do something
Autoboxing problems doesn't apply here as well when check() is declared to return int. If it had returned Integer, then you may risk NullPointerException when assigning it to an int instead of Integer. Assigning it as an Integer and using the if-else block would then indeed have been mandatory.
To learn more about autoboxing, check this Sun guide.
instead of declaring as int i declare it as Integer i then we can do i=null;
Integer i;
i=null;
Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so
public int getHeight(String name){
if(map.containsKey(name)){
return map.get(name);
}else{
return -1;
}
}
No, but int[] can be.
int[] hayhay = null; //: allowed (int[] is reference type)
int hayno = null; //: error (int is primitive type)
//: Message: incompatible types:
//: <null> cannot be converted to int
As #Glen mentioned in a comment, you basically have two ways around this:
use an "out of bound" value. For instance, if "data" can never be negative in normal use, return a negative value to indicate it's invalid.
Use an Integer. Just make sure the "check" method returns an Integer, and you assign it to an Integer not an int. Because if an "int" gets involved along the way, the automatic boxing and unboxing can cause problems.
Check for null in your check() method and return an invalid value such as -1 or zero if null. Then the check would be for that value rather than passing the null along. This would be a normal thing to do in old time 'C'.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
An int is not null, it may be 0 if not initialized. If you want an integer to be able to be null, you need to use Integer instead of int . primitives don't have null value. default have for an int is 0.
Data Type / Default Value (for fields)
int ------------------ 0
long ---------------- 0L
float ---------------- 0.0f
double ------------- 0.0d
char --------------- '\u0000'
String --------------- null
boolean ------------ false
Since you ask for another way to accomplish your goal, I suggest you use a wrapper class:
new Integer(null);
I'm no expert, but I do believe that the null equivalent for an int is 0.
For example, if you make an int[], each slot contains 0 as opposed to null, unless you set it to something else.
In some situations, this may be of use.

Check if array entry was already exists in Java

I have a rather simple question: How to check for an (int) array, whether the current entry array[i] was already assigned or not.
It is a dynamic programming task, where I store results for sub-tasks in an array. Thus the array is filled continuously.
I tried: if(a[i] != null) do stuff; but I got an error that "!=" is a bad operator in this case.
What would be the best(robust) solution to check this?
If a is an int array, you can't ask this:
if (a[i] != null)
Because an int value cannot be null. In an empty int array, the uninitialized positions will have 0 as value. Maybe this will work for your use case?
if (a[i] != 0)
If that doesn't solve the problem, then consider explicitly initializing the array with a different value (for example: -1), at the beginning of your program, and testing against it in the condition.
(a[i] != null) is an error for the int type. This is because int is a primitive type and cannot be null. As explained in another answer and some comments, you can fill the array with a set value such as -1 or Integer.MIN_VALUE which would flag an unused element.
If you need a value that can be null and passed as an object, perhaps an array of Integer will do.
It is initialized almost the same:
Integer[] a = new Integer[N]; // N is a constant indicating the length of the array
This creates an array that can hold Integer objects, all of which are initialized to null. You can put an Integer into the array with:
a[i] = new Integer(x);
This will work fine in your if statement:
if (a[i] != null) {...do something...}
will work fine.

How to check if my array is not the same as the original?

IN JAVA
I have an array like the fallowing:
int[] board={0,0,0}
If I change it to something like:
board[1,2,3]
I want to check if my current board is equal to the previous board:
if (board[0,0,0] != board[1,2,10]){
System.out.print("Its full")
}
And I want to get if it's right or wrong.
You'll have to create a copy of the original array in order to be able to compare it to the new state of the array.
The comparison itself can be done with
Arrays.equals(originalArray, currentArray)
You need to check the elements individually. Loop through one array comparing to values of other array:
boolean same = true;
for(int i = 0; i < board.length; i++)
{
if(board[i] != board2[i]
{
same = false;
break;
}
}
if same is true then they are the same if not then they are not the same.
Use the Arrays class:
if(!Arrays.equals(board1, board2))// check whether boeard1 and boeard2 contains the same elements
System.out.print("Its full")
Try with Arrays class from http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html.
boolean equals = Arrays.equals(array1, array2);
In Java, there is a utility class called Arrays, which has an equals() overloaded method that you can use to compare if two arrays have the same values in each position.
Check the Oracle Documentation about Arrays.equals()

Checking Array for null element

So I've created my own class with 5 private fields: Each is an array with a pre-set length. It's my way of creating a table, where each array is a column, and they have pre-set lengths because not every cell will contain an element (So, not using anything dynamic).
Anyway, my question is: Can I check to see if a specific cell of a specific array contains "null"? Using .equals(null) gives a nullpointerexception :(
When you call .equals(...) you call a method of the object. If it is null, it has no method. Therefore null check like this:
if (myArray[position] == null) {
....
}
don't do .equals(null) but == null:
if( the_array[i] == null ) {
//...
}
Think about build a table by a bidimensional array. Example:
TheClass my_array[][] = new TheClass[10][5];
you should use
if (cell[i] == null){
}
since you are testing for reference equality. And in the case where cell[i] is actually null, null doesnt have an equals method.
Mixed up for loops and null construct
for(Integer ints : intNum) {
if(intNum != null) {
//valid
}
}
I'm more curious as to why your making 5 arrays? Have you heard of multidimensional arrays? Maybe that's what you really need in this case.
an array like this fx:
int[][] arrayName = new int[3][3];
Would represent an array of 3 rows and 3 columns in each.
Maybe you alrdy knew that, but it just seems weird to me to make five different arrays if you just want a table-like structure.

Comparing variables of objects in an array?

I've an array of objects in Java. Say these objects Obj contain a variable var, and I have several Obj stored in an array Array[].
I'd like to compare the var between two adjacent Obj but I don't know how, nor can I find any info online (which makes me think i'm working my question wrong or it's not doable or something)
Edit:
I'm currently attempting the rather roundabout method of assigning the array objects in question to new temporary objects and just doing the comparison with those:
Obj o1 = o[i];
Obj o2 = o[i+1];
if (o1.var > o2.var)
//etc
But surely there is something better.
If you have an array of objects, you can do your comparison without creating the temporary references:
MyObject[] arr = //populated somehow
for (int index = 0; index < arr.length - 1; index++) {
if (arr[index].var > arr[index + 1].var) {
//your logic
}
}
You might also want to take a look at the Comparable interface as a means of encapsulating the comparison of the objects based on a particular field. Using this interface would allow you to take advantage of its support in the Collections API.
Based on your edit, it would be fine to say
if (o[i].var > o[i+1].var) { ... }
assuming that o was of type Obj[].
I'm curious, though: are you trying to sort the array? If so, you can use Arrays.sort() (If not, it's a good method to know about anyway.)
I may not be understanding your question correctly, but the following is perfectly valid:
if (o[i].var > o[i+1].var ) { // ...etc... }
Beware of when you hit the end of the array! That is, if you are looping through all of the elements and i is the last one, then o[i+1] will give you an Array Index Out of Bounds error!
Just use them directly without the reference i.e. substitute the array lookup into where you are doing the comparison.
if (o[i].var > o[i+1].var) {
// etc
}
Or in a loop, doing every one programmatically:
for (int i=0; i<o.length-1; i++) {
if (o[i].var > o[i + 1].var) {
// etc
}
}

Categories