如何避免在对象数组列表中添加重复项

编程入门 行业动态 更新时间:2024-10-18 12:25:47
本文介绍了如何避免在对象数组列表中添加重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个'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); }

更多推荐

如何避免在对象数组列表中添加重复项

本文发布于:2023-11-07 06:01:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565726.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!