Checking Array for null element - java

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.

Related

Java printing empty array error

This is my very simple code, with data being an empty double array
private void findLast(){
double empty[] = new double[0];
if(data == empty){
throw new ArrayIndexOutOfBoundsException(" Array is empty");
}else{
System.out.println(data[data.length-1]);
}
}
When I run the code I get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
My question is, shouldn't the "throw" and "if" stop the "else" from running? And how do I fix the code so it runs properly?
== tests for reference equality for reference types such as arrays.
empty == empty is true
empty == new double[0] is false.
If you need to find if an array is empty, use:
if (data.length == 0) {
In java, the == operator checks if the two variables reference the same object, not if the two objects that the variables reference have equivalent values. So, even if both empty and data are double arrays of size 0, data == empty will never be true because they don't reference the same object.
As a side note, I'm not really sure there's any good reason for you to be doing this and an array of size 0 doesn't have an element at length - 1. If empty has zero elements, what is the point of creating it? if it doesn't have zero elements and you want to know if there is nothing stored into it, then you should know that arrays always have something stored in them after being initialized.
if(data.length==empty.length)
{
throw new ArrayIndexOutOfBoundsException(" Array is empty");
}else{
System.out.println(data[data.length-1]);
}

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()

Working with an Array of Objects

#edit IT works, thanks for the answers:) I guess my bad was when I thought that
WORLD[i]=global.Values.CHUNKPATTERN();
simply takes the object on the right, clones its value('s), and assigns them to part on the left, while it turns out that it establishes a reference between two. Thanks again:)
I have simple begginer/newbie array problem:
for(int i=0; i<global.Values.WORLDVOLUME(); i++)
// global.Values.WORLDVOLUME() --> const, int. always the same.
{
WORLD[i]=global.Values.CHUNKPATTERN(); //to pre-define as 'zero only' object. Always the same. Const.
WORLD[i].chunknr=i+1;
}
System.out.println(WORLD[4].chunknr);
Of course I want WORLD[0] to have chunknr 1, WORLD[4] to have chunknr of 5 and so on.
Instead WORLD[i].chunknr=i+1; seems to update chunknr of ALL elements(not only WORLD[i]).
So that it looks like WORLD[0].chunknr = WORLD[1].chunknr=global.Values.WORLDVOLUME() here.
Anyone knows how to bypass that? I belive there's a simply solution...
Do I understand the array of objects correctly?
You can Have like(providing you have the class and constructor)
Point POINTARRAY[]= new Point[10];
POINTARRAY[1].x=5
POINTARRAY[1].y=6
POINTARRAY[3].x=17
POINTARRAY[3].y=1
Right?
How to assign that via loop?
Instead WORLD[i].chunknr=i+1; seems to update chunknr of ALL elements.
Are WORLD[0] and WORLD[1] different objects? They are not different if `WORLD[0] == WORLD[1] evaluates to true.
You have:
WORLD[i]=global.Values.CHUNKPATTERN();
Does CHUNKPATTERN create a new object every time it is called?
I bet this method
WORLD[i]=global.Values.CHUNKPATTERN();
always returns the same instance of an object so you have a reference to the same object in every slot of your array.
Subsequently
WORLD[i].chunknr=i+1;
you change the attribute chunknr of the same object in every iteration. You say
...seems to update chunknr of ALL elements
kind of true, because all elements reference the same instance.
You need to find a way to have global.Values.CHUNKPATTERN(); return a new object every time.
This line is your problem:
WORLD[i]=global.Values.CHUNKPATTERN();
This is assigning WORLD[i] a reference to global.Values.CHUNKPATTERN(), meaning that they both point to the same object! And for each iteration of your loop you are just creating more and more references to the same global object.
Sometimes this isn't what you want. In this case you need to copy the value, which can be done in a number of ways, but in most cases you can simple clone it. All Java objects support a clone() method, although sometimes you need to override it to do the correct thing for your class.
All this means is that you should replace the above line with:
WORLD[i]=(YourType)global.Values.CHUNKPATTERN().clone();
where YourType is the actual type of the class, since you omitted that from the code snippet you posted.
Hope that helps!
I guess the following line returns always the same reference:
global.Values.CHUNKPATTERN();
so the different array indices are actually point to the same referece. It's only a guess because you didn't tell us how the above function works.
Here's an example of what different array element could point to the same instace:
public class AClass{
public int val = 0;
}
AClass[] array = new AClass[2];
AClass classInstance = new AClass();
array[0] = classInstance;
array[1] = classInstance;
The code above instatiated a single AClass object (classInstance), but use 2 different array elements to reference the same instance:
System.out.println("array 1 value " + array[1].val ); // both element initialized to 0 so it prints 0
array[0].val = 15; // actually is classInstance.val to be modified, through the reference to it stored inside the first element of the array.
System.out.println("array 1 value " + array[1].val ); // print 15
For what concern the POINT example, you can use for loop this way:
Point POINTARRAY[]= new Point[10];
for(int i = 0 ; i < POINTARRAY.length; ++i)
{
POINTARRAY[1].x=...;
POINTARRAY[1].y=...;
}

How do I check if an array element exists?

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.

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