search in java ArrayList

前端 未结 8 1895
别跟我提以往
别跟我提以往 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条回答
  •  心在旅途
    2020-12-03 05:48

    Others have pointed out the error in your existing code, but I'd like to take two steps further. Firstly, assuming you're using Java 1.5+, you can achieve greater readability using the enhanced for loop:

    Customer findCustomerByid(int id){    
        for (Customer customer : customers) {
            if (customer.getId() == id) {
                return customer;
            }
        }
        return null; 
    }
    

    This has also removed the micro-optimisation of returning null before looping - I doubt that you'll get any benefit from it, and it's more code. Likewise I've removed the exists flag: returning as soon as you know the answer makes the code simpler.

    Note that in your original code I think you had a bug. Having found that the customer at index i had the right ID, you then returned the customer at index id - I doubt that this is really what you intended.

    Secondly, if you're going to do a lot of lookups by ID, have you considered putting your customers into a Map?

提交回复
热议问题