views:

276

answers:

3

If I have an LinkedList of Employee objects...

Each employee has a Name, and an ID fields.

I have linkedList call list....

If I want to see if the list contains an employee I do:

list.contains(someEmployeeObject)

How about if I want to see if the the list contains an employee based on the imployee ID..

let's say I have the following method:

public boolean containsEmployeeByID(int id)

How can I know if the list contains the employee object with the parameter id?

+3  A: 

Just walk the list and look for matches. If you do this often and change the list infreqently, build a Map index first.

List<Employee> list = ...
for (Employee e : list)
   if (e.getID() == id)
      return true;
return false;

That said, saving employees in a LinkedList?? What a strange example problem...

Chris Dolan
just a homework assignment...
Then to be honest, you should tag the question as homework. I've done it for you this time...
Chris Dolan
true, only in homework someone would possibly keep employee records in a linked list :)
Omry
+1  A: 

Maybe you should be using a map with the key being an ID and value being the employee name or the employee object?

Joe Philllips
Sets don't have values. You mean a Map.
Chris Dolan
Indeed. Fixed........................
Joe Philllips
But of course, to build the Map you need to walk the LinkedList...
Chris Dolan
A: 

You could override your equals() method to compare based on Id, however this typically is not a best practice.

Another option is to create a HashMap and then you can retrieve your employees by their Id.

for (Employee empl : list) {
    map.put(empl.getId(), empl);
}

String idLookup = "1234";

Employee employee = map.get(idLookup);
zmf