Why would someone initialize an object = -1?
int index = -1;
we use this code to search for an object in an array. eg.
for(int i = 0; i < bArrayList.size(); i++) {
if ( bAcc == bArrayList.get(i).getANum() ) {
index = i;
}
}
Why would someone initialize an object = -1?
int index = -1;
we use this code to search for an object in an array. eg.
for(int i = 0; i < bArrayList.size(); i++) {
if ( bAcc == bArrayList.get(i).getANum() ) {
index = i;
}
}
With an int
you can not set it to null
. People commonly use -1 to represent null or nothing found in return. They do this because when you do loop through stuff it starts at 0 not 1.
For example, say you have a function to get the index of a certain item in an array. If the array does not have what you are looking for, returning 0 represents index: 0 and you can not return null because it is an integer, so instead you would return -1.