How to retrieve particular emp object from a list without looping through datastructure
I have 65000 records of employees in a database . i am retreiving all the 开发者_运维百科records and storing as employee object in a list as a cache. when customer enters the emp id in the browser , the record should be fetched from the list on one condition , without looping through the list. how can we acheive it.
using indexOf(Object ) we can acheive ,by implementing equals method , but what business logic should go in that.kindly let me know your views.
class Employee
{
private int id;
private String name;
Private String address;
public void setAddress (){}
public void setId(){}
public void setName(){}
// simillarly getMethods
}
1) I would implement a cache based on a hashmap rather than a list:
Map cache = new HashMap<Integer, Employee>();
This way you can retrieve an Employee object by a given ID very efficiently.
Additionally, I wouldn't add a setter for the employee id, since it can corrupt the mapping. Consider setting the id through a constructor parameter only.
--EDIT--
If you MUST use a list:
2) You may want to sort it first. This will allow performing a binary search (See Collections.binarySearch(..) methods). This requires implementing a Comparator or the Comparable interface, in order to define an ordering between the Employee objects. Also, you will have to create a dummy Employee object with the required id each time you want to perform the search.
3) If performance is not an issue, simply use List.indexOf(..). This requires implementing the equals(..) method in the Employee class.
4) In order to do it really without loops, you can create a sparse list, containing Employee with id N at index N. This is only feasible if the Employee id value range is not too big. The benefit is an optimal retrieval time.
精彩评论