tags:

views:

28

answers:

1

Guys , 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
}
A: 

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.

Eyal Schneider
@Eyal i dont want using Map. only by List .
Suresh S
@Eyal any idea how to do in list!!
Suresh S
@Suresh S: @Eyal Schneider's suggestion is pretty much the best solution in your case. Why would you prefer a list over a Map if you want access-by-key?
FK82
this was a interview questions,intially i suggested using HashMap,but she was asking to use list.
Suresh S
@Eyal thanks for the idea. what logic must go in to equals method to return particular object.
Suresh S
@Suresh S: check http://java.sun.com/javase/6/docs/api/java/util/Comparator.html#equals(java.lang.Object) .
FK82