How to avoid adding duplicate entries in an arraylist of objects

别说谁变了你拦得住时间么 提交于 2020-06-23 14:10:26

问题


I have a class 'Employee' which has attributes (Designation, DoB, Employee-I'd, Name, Salary).

Now through the following function I'm adding 'n' employee objects in the ArrayList 'abc'

But I need to modify it in such a way that if an end user tries to add a duplicate employee (If name of two employees are same then it should be considered as duplicate) then the user is not allowed to do so...

How can I do this... I think probably using Map Interface... But no idea, how to implement

public void addEmployees(int n, ArrayList<Employee> abc)    /* 'n' is the number of employees to be added */
{
    Scanner sc=new Scanner(System.in);
    Employee[] obj = new Employee[n];
    for(int i=0;i<n;i++)
    {
            System.out.println("Enter Employee name:");
            String nm=sc.next();
            System.out.println("Enter designation:");
            String des = sc.next();
            System.out.println("Enter employeeI-D:");
            int eId = sc.nextInt();
            System.out.println("Enter salary:");
            double sl = sc.nextDouble();
            System.out.println("Enter date-of-birth:");
            String dt=sc.next();
            obj[i]=new Employee(des,dt,eId,nm,sl);
            abc.add(obj[i]);
    }
}

回答1:


An ArrayList (or any sort of List) is a suboptimal data structure for this problem as element lookup takes O(n) time where n is the size of the list. Basically you need to go through the whole list and check if that element is there:

public boolean contains(List<Employee> employees, Employee emp) {
    for(Employee el : employees) {
        if(el.equals(emp)) { // override equals() and hashCode() in Employee 
                             // or use a cutom equals(Employee, Employee) method
            return true;
        }
    }
}

Or with Java 8 syntax:

abc.stream().anyMatch(emp -> emp.equals(newEmployee));

If you can change that list to a Set then you can use the contains(Element) method to check if the Set already contains a given element. Be aware that this method uses equals method to do the check!




回答2:


To be able to check for duplication, we can store the names in a set(Set< String > names), and check it every time before adding an employee to the list:

Employee[] obj = new Employee[n];
Set<String> names = new HashSet<String>();
...........
...........
if (!names.contains(nm) {
    abc.add(obj[i]);
    names.add(nm);
}


来源:https://stackoverflow.com/questions/31846329/how-to-avoid-adding-duplicate-entries-in-an-arraylist-of-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!