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

后端 未结 8 1323
名媛妹妹
名媛妹妹 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:13

    You have to loop through the entire array, there's no changing that. You can however, do it a little easier

    for (Dog dog : list) {
      if (dog.getId() == id) {
        return dog; //gotcha!
      }
    }
    return null; // dog not found.
    

    or without the new for loop

    for (int i = 0; i < list.size(); i++) {
      if (list.get(i).getId() == id) {
        return list.get(i);
      }
    }
    

提交回复
热议问题