user69514
user69514

Reputation: 27629

Finding element in LinkedList

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?

Upvotes: 1

Views: 11845

Answers (3)

zmf
zmf

Reputation: 9303

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);

Upvotes: 1

Joe Phillips
Joe Phillips

Reputation: 51110

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

Upvotes: 1

Chris Dolan
Chris Dolan

Reputation: 8963

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

Upvotes: 4

Related Questions