Java Collections. Collection for an Employee Store

假如想象 提交于 2019-12-24 08:28:27

问题


Hey im just wondering what would be the best collection to use when creating a store for employee details such as name, age address, dob, wages and email address. the store needs all the bare essentials such as add, edit, remove, remove all and searchBy.


回答1:


Well you'd probably want a fast search, so a hashing structure with the key as the fiend you want to search by could be the best solution. For example, if you want to search by name, you can create a class like this:

public class EmployeeStore {
    private Map<String, Employee> employees;

    public EmployeeStore() {
        employees = new HashMap<String, Employee>();
    }

    public void add(Employee e) {
        employees.add(e.getName(), e);
    }

    public Employee searchByName(String name) {
        return employees.get(name);
    }

    // etc.
}

and implement the required methods based on your needs using the employees data structure. If the search is done by name you can have the name as the key string.

Unfortunately, searching by a different field than the index will require a linear search which will be slow if you have a huge number of entries.




回答2:


Simply create a class for your employee entity like something below:

public class Employee
{
String name;
public void setName(String nm)
{
this.name=nm;
}
public String getName()
{
return this.name;
}
//Other variables and associated getter and setters
}

Now you can create a collection of Employee objects:

ArrayList<Employee> employees=new ArrayList<Employee>();

Or you may use any other collections you want.

Then you need to implement some logics for the methods you want like

Update(), Delete()

You should use HashMap or Map for faster search capability!




回答3:


The specific "best" collection to use will depend on the access needs and the data constraints. But you might encapsulate multiple collections in a single EmployeeStore class for access in multiple ways.

If you need for example to search by name, and can guarantee names are unique, a Map<String, Employee> with names stored as key would allow you to quickly find an employee with a given name. If the names are not guaranteed to be unique, you might need instead a Map<String, List<Employee>>.

For searches based on other fields, you could maintain other maps with the appropriate keys.

The implementations of your add, remove and edit methods would of course have to update all the maps you use appropriately.

If your searches are more complex than simple lookups by key, or if your data is large, you likely need to back your EmployeeStore with a database instead of just using collections.



来源:https://stackoverflow.com/questions/11275669/java-collections-collection-for-an-employee-store

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