-1

Say we have an array, and we have an if sentence that check if the content of the array[i] is the same. For example we have an Person[] array = new Person[10]; And we are gonna return the Person in the array that has the name "Tom".

Then we would make a for-loop and check every element or slot in the array.

if(Person[i].getName().equals("Tom")) or == "Tom" . Do we need an if-sentence that check if the Person[i] != null? Is there ny point, will it limit the amount of null pointer exceptions?

  • 7
    If there is a `null` in the `Person[] array` then yes, if you remove that `null` check you might get a `NullPointerException`. – Elliott Frisch Nov 10 '14 at 21:43
  • 1
    Possible duplicate: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java – martinez314 Nov 10 '14 at 21:45
  • 2
    It is second time in last 20 minutes I see `method` `dot` `arguments`. Who told you guys to use `getName.("Tom")` instead of `getName("Tom")`? – Pshemo Nov 10 '14 at 21:46
  • Depends if a null could ever get into the array (and it not be a mistake). Preferably it couldn't ever get in. If there is one what does it mean? Silently hiding problems is always a bad idea but if null is legitimate you'll have to check for it – Richard Tingle Nov 10 '14 at 21:47
  • `"Tom".equals(person[i].getName())` – David Conrad Nov 10 '14 at 21:55

2 Answers2

2

why not just use:

if(Person[i] != null && Person[i].getName("Tom"))

Is there ny point, will it limit the amount of null pointer exceptions?

Of course it would limit the amount of null pointer exceptions, if you had a null for Person[i]

austin wernli
  • 1,801
  • 12
  • 15
0

I think it would be best to design your code in a way that no null elements are in the array. Anyway, in Java 8 you can do this:

Person[] persons = ...
List<Person> result = Arrays.stream(persons)
                            .filter(Objects::nonNull)
                            .filter(p -> "Tom".equals(p.getName()))
                            .collect(Collectors.toList());

The result list contains all Persons with name "Tom".

eee
  • 3,241
  • 1
  • 17
  • 34