最近我参加了一次关于在DS中保存大量员工详细信息的面试。
我提出了使用员工ID作为键的HashMap解决方案。
接下来的问题是,如果用户想按姓名搜索如何实现。我建议使用员工姓名作为键,并将所有具有相同姓名的员工保存为ArrayList。
接下来的问题有些棘手,需要创建一个映射,用户可以根据员工ID或员工姓名进行搜索。如何在映射中实现这一点?
以内存高效的方式实现它。
最近我参加了一次关于在DS中保存大量员工详细信息的面试。
我提出了使用员工ID作为键的HashMap解决方案。
接下来的问题是,如果用户想按姓名搜索如何实现。我建议使用员工姓名作为键,并将所有具有相同姓名的员工保存为ArrayList。
接下来的问题有些棘手,需要创建一个映射,用户可以根据员工ID或员工姓名进行搜索。如何在映射中实现这一点?
以内存高效的方式实现它。
Map<?, List<Employee>> map = new HashMap<>();
public void putEmployee(Employee e) {
map.put(e.id, Arrays.asList(e)); // put by id
if (!map.containsKey(e.name)) {
map.put(e.name, new ArrayList<>());
}
map.get(e.name).add(e); // put by name
}
public Employee getById(long id) {
return map.containsKey(id) ? map.get(id).get(0) : null;
}
public List<Employee> getByName(String name) {
return map.containsKey(name) ? map.get(name) : Collections.emptyList();
}
在生产代码中,我会使用两个单独的地图或自定义字典类。
Map<Integer, Employee> employeesById;
Map<String, Set<Employee>> employeesByName;
Map<Object, Object>
- 混合键类型和混合值类型。如果这样做可以完成工作,那么为什么不呢?但是你必须牺牲Java的强类型检查来实现它,而且这并不是必要的,也没有实际帮助。如果面试问题只是一个“谜题”,不打算用于生产,那么你的解决方案是很好的 - 它不比要求你只使用一个map的人为和糟糕的设计要差。 - BohemianKey
对象:public enum KeyType {
ID, NAME;
}
public class SearchKey {
private KeyType keyType;
private String value;
// constructor and getters snipped for brevity's sake
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SearchKey searchKey = (SearchKey) o;
return keyType == searchKey.keyType && value.equals(searchKey.value);
}
@Override
public int hashCode() {
int result = keyType.hashCode();
result = 31 * result + value.hashCode();
return result;
}
public class Directory {
private Map<SearchKey, Set<Employee>> directory = new HashMap<>();
public void addEmployee(Employee e) {
// Add search by id
directory.put
(new SearchKey(KeyType.ID, e.getId()), Collections.singleton(e));
// Add search by name
SearchKey searchByName = new SearchKey(KeyType.NAME, e.getName());
Set<Employee> employees = directory.get(searchByName);
if (employees == null) {
employees = new HashSet<>();
directory.put(searchByName, employees);
}
employees.add(e);
}
public Employee getById (String id) {
// Assume that the ID is unique
return directory.get(new SearchKey(KeyType.ID, id)).iterator().next();
}
public Set<Employee> getByName (String name) {
return directory.get(new SearchKey(KeyType.NAME, name));
}
}
Map<?, Employee>
变体 - Alex Salauyou
Map<Employee,String>
- SatyaTNV