简体   繁体   中英

Element's equality check from list of object

I have a List of Employee object.

class Employee{  
  private int empId;  
  private String name;  
}  

Now I have

List<Employee> empList = new ArrayList<Employee>();  

How can I find, if my list contains an employee named "ABC"??
empList.contains("ABC"); wont work...

Should I put it in Map ?? Which one is more efficient??

Just wanted to mention that I get my Employee object from database....

You can use

Map<String, Employee> map = new HashMap<>();
map.put("ABC", new Employee("ABC"));
map.put("John", new Employee("John"));

and then check

map.containsKey("ABC")


Should I put it in Map?? Which one is more efficient??

Because contains() method of list, calls indexOf , which needs to iterate over all elements like this

public int indexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < size; i++)
            if (elementData[i]==null)
                return i;
    } else {
        for (int i = 0; i < size; i++)
            if (o.equals(elementData[i]))
                return i;
    }
    return -1;
}

Where as map no need to iterate over all elements

Override equals. You can then use List.contains

class Employee {  
    private empId;  
    private name;
    public boolean equals(Object o) {
        return (o instanceof Employee && ((Employee)o).empId == empId && ((Employee)o).name = name);
    }
}  


List l = ...;
Employee e = new Employee(...);
l.add(e);
l.contains(e);

Since you are storing the Employee objects and not String in your list , i think it is impossible to search without looping through all list objects

for (Employee employee : empList) {
      if (employee.getName().equals(searchString))
        System.out.println("Found");
    }

Note: Your Employee class should give access to name field either through getter method or change it to public


There are other alternatives, but it depends on your requirements and tradeoff's between speed, space, readability, resources etc

One thing i can think of is HashMap , which has constant time lookup in average case

HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1, "Tom");
System.out.println(hm.containsValue("Tom"));

Now,

Should I put it in Map?? Which one is more efficient??

Instead of coding and analyzing, Know Thy Complexities beforehand !

在Java 8中,如果要确定员工列表中是否包含名为“ ABC”的员工,则可以执行以下操作:

boolean containsABC = empList.stream().anyMatch(emp -> emp.getName().equals("ABC"));

Here is the code that you can use. I am considering that you want list to return true when empId and name of the Employee matches.
I also prefer to use Constructor in your code(Just recommendation).
The below code will run as you are wanting it to be.

class Employee {

    private int empId;
    private String name;

    // below overriden function will return true if it found Employee with 
    // same ID and name
    @Override
    public boolean equals(Object obj) {
        return (obj instanceof Employee             //Checking instace of obj
            && ((Employee)obj).empId == empId       //Checking empId
            && ((Employee)obj).name.equals(name));  //Checking name
    }

    // Used constructor to create Employee
    Employee(int id, String nm) {
        empId = id;
        name = nm;
    }

}


Here is an example run :

List l = new ArrayList();
l.add(new Employee(1, "ME");
System.out.println(l.contains(new Employee(1, "ME")));  //print true

I would also like to acknowledge you that you should also override hashCode() when you decides to override equals(...) method according to Design Pattern .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM