Looking for value in List
collections, java, list
Solution
Collections.sort(employees); // BigO - nlog(n)
int index = Collections.binarySearch(employees, new Employee("abc",...)); // BigO - log(n)
if you sort every time your list and search it, Code complexity would be `nlog(n) + log(n)` where `nlog(n)` for sorting list and `log(n)` for binary search.
It is better if you search your list linearly. liner search would take `BigO - n` which perform better than previous approach.
You are getting `cast Exception` in `Collections#sort` method because of your list contain `null value` which unable to cast Employee and raise `ClassCastException`
Problem
I have List declared as ``` private List<Employees> employees; ``` and in I am getting values from database using DAO as ``` employees= new ArrayList<Employees>(); employees.addAll(myDAO.getEmployees()); ``` I would like to search for a value in `employees List`, what is the best approach for looking for a value in `employees List`? I have tried ``` Collections.sort(employees); int index = Collections.binarySearch(employees, "abc"); ``` However I am getting cast Exception Any help is highly appreciated. Thanks