search in java ArrayList

前端 未结 8 1886
别跟我提以往
别跟我提以往 2020-12-03 05:04

I\'m trying to figure out the best way to search a customer in an ArrayList by its Id number. The code below is not working; the compiler tells me that I am mis

8条回答
  •  Happy的楠姐
    2020-12-03 06:09

    Even if that topic is quite old, I'd like to add something. If you overwrite equals for you classes, so it compares your getId, you can use:

    customer = new Customer(id);
    customers.get(customers.indexOf(customer));
    

    Of course, you'd have to check for an IndexOutOfBounds-Exception, which oculd be translated into a null pointer or a custom CustomerNotFoundException.

提交回复
热议问题