我有一个List
Employee
个对象。
class Employee{
private int empId;
private String name;
}
现在我有了
List<Employee> empList = new ArrayList<Employee>();
如果我的列表中包含名为“ABC”的员工,我怎么能找到?
empList.contains("ABC");
不会工作......
我应该把它放在Map
??哪一个更有效率?
只是想提一下我从数据库中获取我的Employee对象....
答案 0 :(得分:1)
您可以使用
Map<String, Employee> map = new HashMap<>();
map.put("ABC", new Employee("ABC"));
map.put("John", new Employee("John"));
然后检查
map.containsKey("ABC")
我应该把它放在地图上吗?哪一个更有效率?
因为列表的contains()
方法,调用indexOf
,需要迭代所有元素
像这样
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;
}
map不需要迭代所有元素
答案 1 :(得分:1)
覆盖等于。然后,您可以使用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);
答案 2 :(得分:1)
由于您在列表中存储了Employee
个对象而不是String
,我认为如果不循环遍历所有列表对象,就无法进行搜索
for (Employee employee : empList) {
if (employee.getName().equals(searchString))
System.out.println("Found");
}
注意:您的Employee类应该通过getter方法访问name字段或将其更改为public
还有其他选择,但这取决于您的要求和速度,空间,可读性,资源等之间的权衡。
我能想到的一件事是HashMap
,其中有constant time lookup in average case
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1, "Tom");
System.out.println(hm.containsValue("Tom"));
现在,
我应该把它放在地图上吗?哪一个更有效率?
而不是事先编码和分析Know Thy Complexities!
答案 3 :(得分:1)
在Java 8中,如果您想确定员工列表是否包含名为&#34; ABC&#34;的员工,您可以这样做:
boolean containsABC = empList.stream().anyMatch(emp -> emp.getName().equals("ABC"));
答案 4 :(得分:0)
以下是您可以使用的代码。
我认为当empId
的{{1}}和name
匹配时,您希望列表返回true。
我也更喜欢在你的代码中使用Constructor(只是推荐)
以下代码将按您希望的那样运行。
Employee
以下是一个示例运行:
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;
}
}
我还要感谢您,当您决定根据设计模式覆盖List l = new ArrayList();
l.add(new Employee(1, "ME");
System.out.println(l.contains(new Employee(1, "ME"))); //print true
方法时,您还应覆盖hashCode()
。