Finding element in LinkedList

11,351

Solution 1

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

Solution 2

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

Solution 3

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);
Share:
11,351
user69514
Author by

user69514

Updated on June 04, 2022

Comments

  • user69514
    user69514 almost 2 years

    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?

    • Brett
      Brett about 15 years
      Note LinkedList read performance isn't great. Even get(int) is slow. ArrayList is almost always a better idea.
  • Chris Dolan
    Chris Dolan about 15 years
    Sets don't have values. You mean a Map.
  • Omry Yadan
    Omry Yadan about 15 years
    true, only in homework someone would possibly keep employee records in a linked list :)