-2

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;
  }
}
Mike Lyons
  • 1,748
  • 2
  • 20
  • 33
Ian Murray
  • 37
  • 4
  • 9
    -1 is somewhat the default value you return for the index if the object you search for in the list or array is not found. Since the indices are valid starting from 0 to [number of elements - 1], if -1 is returned, you know the element is not found. – Stultuske Apr 20 '15 at 16:16
  • 4
    possible duplicate of [Is -1 a magic number? An anti-pattern? A code smell? Quotes and guidelines from authorities](http://stackoverflow.com/questions/3031975/is-1-a-magic-number-an-anti-pattern-a-code-smell-quotes-and-guidelines-from) – Alex Salauyou Apr 20 '15 at 16:18
  • 1
    Please do not call a primitive data type variable in java "object". This is misleading. – Laszlo Hirdi Apr 20 '15 at 16:34

1 Answers1

1

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.

Forseth11
  • 1,418
  • 1
  • 12
  • 21