-4

I am trying to compare two int values with a method.

I have put two get methods after each other because the array[i] is a list of person objects and gethouse only gives the house object, the houseid is in another class.

I'm wondering if I can set up two get() methods after each other?

public Person findperson( int houseId ){

    for ( int i = 0; i < array.length; i++ ){
        if ( array[ i ].gethouse().gethouseID() == houseId  ){
            return array[ i ];
        }
    }
    return null;
}
chrisbunney
  • 5,819
  • 7
  • 48
  • 67

3 Answers3

1

If your house class (whatever is returned from gethouse() implements gethouseID(), the person instance at array[i] is not null, AND gethouse() returns something non-null, this will work fine. Otherwise, this will bomb out with either a compilation failure, or at runtime with a null pointer exception. You're safer to get the person, check it for null, get the house, check it for null, then get the houseID and compare to the one you're looking for.

David
  • 2,602
  • 1
  • 18
  • 32
1

You can do this.

However I don't think it's good practise.

  1. my first concern is the potential for null pointer exceptions (NPEs). If you write a.getB().getC().getD(), any one of these can return null. You can't tell which returned null in the resulting stack trace (excluding the last invocation returning null, which is fine). You may wish to use the null object pattern in this scenario.
  2. my second concern is more design-oriented. You're asking A for info about what it knows, then asking that result, and so on and so forth. Objects exist to do things for you, so you should do just that, and let your objects work for you. Get your Person object to do the heavy lifting.
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • if i remember in java 7 you can check null pointer by doing a?.getB()?.getC()?.getD()... etc – user902383 Oct 26 '12 at 13:40
  • That was rejected, I believe. http://stackoverflow.com/a/4390187/12960. But anyhow, it gives you a null. That may/may not be what you want – Brian Agnew Oct 26 '12 at 13:46
0

First you get a Person object, then with calling gethouse() you get a house object and then you call gethouseID() to get the Integer. This should absolutely be possible.

John Frost
  • 673
  • 1
  • 10
  • 24