Java method: Finding object in array list given a known attribute value

后端 未结 8 1444
名媛妹妹
名媛妹妹 2020-12-16 11:43

I have a couple of questions actually.

I have a class Dog with the following instance fields:

private int id;
private int id_mother;         


        
8条回答
  •  清酒与你
    2020-12-16 12:04

    I was interested to see that the original poster used a style that avoided early exits. Single Entry; Single Exit (SESE) is an interesting style that I've not really explored. It's late and I've got a bottle of cider, so I've written a solution (not tested) without an early exit.

    I should have used an iterator. Unfortunately java.util.Iterator has a side-effect in the get method. (I don't like the Iterator design due to its exception ramifications.)

    private Dog findDog(int id) {
        int i = 0;
        for (; i!=dogs.length() && dogs.get(i).getID()!=id; ++i) {
            ;
        }
    
        return i!=dogs.length() ? dogs.get(i) : null;
    }
    

    Note the duplication of the i!=dogs.length() expression (could have chosen dogs.get(i).getID()!=id).

提交回复
热议问题