Check if array entry was already exists in Java - 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.

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 an int ( not from DataBase) is null

such as int a, how can I judge a is null? a is not from DataBase.
As when the data is transferred from Internet, the value of a may be missing.
I need to check whether a is null.
-----add-----
Such As Class A has a private int a, not initial. A has a SetA() function.
May be transfer from Internet, can the A != null but A.a is not value?
You can use ResultSet.getObject() to return a Java Object instead of working with a primitive int:
Integer val = resultSet.getObject("val") != null ? resultSet.getInt("val") : null;
In this case, a null value will really correspond to a null in your database table, and a value of 0 will correspond to this exact value.
Note that if you try something like this:
int val = resultSet.getInt("val");
if (val == 0) {
// but 0 can mean null OR the actual value 0...
}
then you won't be able to distinguish a null value from the actual value 0.
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;
And Most Importantly
int can't be null, but Integer can.
Try this
if(a == null){
//try something
}
here the a instant of Integer.
Default value of primitive cannot be null. For int it should be 0.
As for data transferred from internet the value may be in string format initially. You can check if the string is null before parsing it to int.

Array Initialization: int versus other Objects

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.

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.

What is inside code for array.length() in Java?

What is stored in 10th location of array
say
int[] array=new int[10];
Say we have values stored from array[0] to array[9], if I were to print elements without using
array.length()
or for (int a: array)
How do I proceed?
My basic question is how will JVM determine end of array, is it when a null is encountered parsing array or when a garbage value is encountered? what is inbuilt code of array.length() function?
What is stored in 10th location of array say
...
my basic question is how will JVM determine end of array, is it when a null is encountered parsing array or when a garbage value is encountered? what is inbuilt code of array.length() function?
Welcome C/C++ programmer :-)
Java uses a different paradigm than C/C++ for arrays. C/C++ uses the terminator/sentinel a.k.a. "garbage") value like NULL to indicate the end of the array. In Java, arrays are more like objects with a special "instance variable"-like variable length that indicates how many slots there are in the array. This special "instance variable" is set at the array's creation and is read-only. Its accessible by saying array.length.
Java expects the code to know when to stop at the end of the array by making sure they don't specify an index greater than length - 1. However, the JVM checks every access to the array for security reasons just in case. If the JVM finds an array index that is less than 0 or greater than length - 1, then the JVM throws an IndexOutOfBoundsException.
What is stored in 10th location of array
Since we can always check the length, there is no need for a marker at the end of the array in Java. There isn't anything special after the last item in the array (it likely will be some other variable's memory).
if I were to print elements without using array.length()
for(int a: array) {
// code of loop body here
}
This code is magically transformed by the compiler to:
for (int i = 0; i < array.length; i++) {
int a = array[i];
// code of loop body here
}
However, the i index variable isn't accessible to the user's code. This code still uses array.length implicitly.
Arrays are objects with a length field. While looping, Java loads the length field and compares the iterator against it.
See 10.7 Array Members in the JLS
Internally, the JVM can track the length of an array however it sees fit. There's actually a bytecode instruction called arraylength that the Java compiler emits whenever you try to get the length of an array, indicating that it's up to the JVM to determine the best way to track the length of an array.
Most implementations probably store arrays as a block of memory whose first entry is the length of the array and whose remaining elements are the actual array values. This allows the implementation to query the length of the array, along with any value in the array, in O(1). If the implementation wanted to, though, it could store the elements followed by a sentinel value (as you've suggested), but I don't believe that any implementations do this because the cost of looking up the length would be linear in the size of the array.
As for how the foreach loop works, the compiler translates that code into something like this:
for (int i = 0; i < arr.length; ++i) {
T arrayElem = arr[i];
/* ... do work here ... */
}
And finally, with regards as to what the 10th element of a 10-element array is, there's no guarantee that there's even an object at that location. The JVM could easily allocate space for the array in a way where there is no tenth element. Since you can't ever actually get this value in Java (it would throw an exception if you tried), there's no requirement that the JVM even have something meaningful there.
Hope this helps!
Define what a "garbage value" is. (Hint: since everything is binary, there is no such thing unless you use a sentinel value, and that's just bad practice).
The length of the array is stored inside the Array instance as a member variable. It's nothing complex.
In a comment on another, the OP writes:
I agree array.length is the conventional method, I was looking for any other option if available.
There is no other reasonable implementation option open to the JVM implementer ... on any mainstream hardware architecture.
In particular, the sentinel approach ONLY detects the case where an application fetches an array element one index beyond the end.
If it fetches 2 or more indexes beyond, then it misses the sentinel and proceeds to access memory whose contents are unknown.
If it stores, then the sentinel is not consulted.
If it needs to directly access the array size as part of the application algorithm, searching for a sentinel is a very inefficient way of doing it. (Not to mention unreliable; e.g. if null is a valid array element.)
Sentinels don't work for (most) primitive arrays because there is no value that can be used as a sentinel. (The idea of a primitive array holding a null is nonsensical from the JLS perspective, since null is not type compatible with any Java primitive type.)
The garbage collector needs an array length in all cases.
In short, the length has to be stored in the array to deal with the other cases. Storing a sentinel as well means you are wasting space storing redundant information, and CPU cycles creating the sentinel and copying it (in the GC).
Okay, here I go :-)
Ways to deal with "arrays" in C
In C there are numerous ways to deal with array. For the remainder I will talk about string* (and use the variable strings which has a type of string*). This is because t[] "effectively decomposes" into t* and char* is the type of a "C string". Thus string* represents a pointer to "C string". This glosses over a number of pedantic issues in C w.r.t. "arrays" and "pointers". (Remember: just because a pointer can be accessed as p[i] doesn't make the type an array in C parlance.)
Now, strings (of type string*) has no way to know it's size -- it only represents a pointer to some string, or NULL perhaps. Now, let's look at some of the ways we can "know" the size:
Use a sentinel value. In this I am assuming the use NULL as the sentinel value (or it might be -1 for an "array" of integers, etc.). Remember that C has no such requirement that arrays have a sentinel value so this approach, like the following two, is just convention.
string* p;
for (p = strings; p != NULL; p++) {
doStuff(*p);
}
Track the array size externally.
void display(int count, string* strings) {
for (int i = 0; i < count; i++) {
doStuff(strings[i]);
}
}
Bundle the "array" and the length together.
struct mystrarray_t {
int size;
string* strings;
}
void display(struct mystrarray_t arr) {
for (int i = 0; i < arr.size i++) {
doStuff(arr.strings[i]);
}
}
Java uses this last approach.
Every array object in Java has a fixed sized which can be accessed as arr.length. There is special byte-code magic to make this work (arrays are very magical in Java), but at the language level this is exposed as just a read-only integer field that never changes (remember, each array object has a fixed size). Compilers and the JVM/JIT can take advantage of this fact to optimize the loop.
Unlike C, Java guarantees that trying to access an index out of bounds will result in an Exception (for performance reasons, even if it were not exposed, this would require the JVM kept track of the length of each array). In C this is just undefined behavior. For instance, if the sentinel value wasn't within the object (read "the desired accessibly memory") then example #1 would have lead to a buffer-overflow.
However, there is nothing to prevent one from using sentinel values in Java. Unlike the C form with a sentinel value, this is also safe from IndexOutOfBoundExceptions (IOOB) because the length-guard is the ultimate limit. The sentinel is just a break-early.
// So we can add up to 2 extra names later
String names[] = { "Fred", "Barney", null, null };
// This uses a sentinel *and* is free of an over-run or IOB Exception
for (String n : names) {
if (n == null) {
break;
}
doStuff(n);
}
Or possibly allowing an IOOB Exception because we do something silly like ignore the fact that arrays know their length: (See comments wrt "performance").
// -- THERE IS NO EFFECTIVE PERFORMANCE GAIN --
// Can ONLY add 1 more name since sentinel now required to
// cleanly detect termination condition.
// Unlike C the behavior is still well-defined, just ill-behaving.
String names[] = { "Fred", "Barney", null, null };
for (int i = 0;; i++) {
String n = strings[i];
if (n == null) {
break;
}
doStuff(n);
}
On the other hand, I would discourage the use of such primitive code -- better to just use a suitable data-type such as a List in almost all cases.
Happy coding.
In terms of how you'd print all the elements in the array without using either a for each loop or the length field, well in all honesty you just wouldn't. You could potentially just have a for loop like the following:
try {
for(int i=0 ; ; i++) {
System.out.println(arr[i]);
}
}
catch(IndexOutOfBoundsException ex) {}
But that's an awful way to do things!
how will you print elements without using array.length or foreach loop
You could of course loop through the array without bounds checking and then catch (and swallow) the ArrayIndexOutOfBoundsException in the end:
try {
int i = 0;
while (true) {
System.out.println(arr[i++]);
}
catch (ArrayIndexOutOfBoundsException e) {
// so we are past the last array element...
}
This technically works, but it is bad practice. You should not use exceptions for flow control.
All array access outside the interval [0, 9] gives an ArrayIndexOutOfBoundsException, not only position 10. So, conceptually you could say that your whole memory (reaching with indexes from Integer.MIN_VALUE to Integer.MAX_VALUE) is filled with sentinel values, apart from the space of the array itself, and when reading or writing to a position filled with a sentinel, you get your exception. (And each array has its own whole memory to spend).
Of course, in reality no one has a whole memory for each array to spend, so the VM implements the array accesses a bit smarter. You can imagine something like this:
class Array<X> {
private final int length;
private final Class<X> componentType;
/**
* invoked on new X[len] .
*/
public Array<X>(int len, Class<X> type) {
if(len < 0) {
throw new NegativeArraySizeException("too small: " + len);
}
this.componentType = type;
this.len = len;
// TODO: allocate the memory
// initialize elements:
for (int i = 0; i < len; i++) {
setElement(i, null);
}
}
/**
* invoked on a.length
*/
public int length() {
return length;
}
/**
* invoked on a[i]
*/
public X getElement(int index) {
if(index < 0 || length <= index)
throw new ArrayIndexOutOfBoundsException("out of bounds: " + index);
// TODO: do the real memory access
return ...;
}
/**
* invoked on a[i] = x
*/
public X setElement(int index, X value) {
if(index < 0 || length <= index) {
throw new ArrayIndexOutOfBoundsException("out of bounds: " + index);
}
if(!componentType.isInstance(value)) {
throw new ArrayStoreException("value " + value + " is of type " +
value.getClass().getName() + ", but should be of type "
+ componentType.getName() + "!");
}
// TODO: do the real memory access
return value;
}
}
Of course, for primitive values the component type check is a bit simpler, since already the compiler (and then the VM bytecode verifier) checks that there are the right types, sometimes doing a type conversion, too. (And the initialization would be with the default value of the type, not null.)

Categories