如何避免在对象数组列表中添加重复项 [英] How to avoid adding duplicate entries in an arraylist of objects

查看:437
本文介绍了如何避免在对象数组列表中添加重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个'Employee'类,该类具有属性(名称,DoB,员工身份,姓名,薪水).

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

现在通过以下功能,我在ArrayList'abc'中添加'n'个雇员对象

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

我该怎么做...我想可能是在使用Map Interface ...但是不知道如何实现

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

推荐答案

为了能够检查是否重复,我们可以将名称存储在一个set( Set< String>名称)中,然后检查每次在将员工添加到列表中之前将其添加:

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

这篇关于如何避免在对象数组列表中添加重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆