Question

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?

Was it helpful?

Solution

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...

OTHER TIPS

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

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top