How to add Array Of Objects - java

How can I Manager class to add an array of Employee objects to the manager class, and create methods to add and remove employees from the Manager
EmployeeTest.java
package com.example;
import com.example.domain.Employee;
import com.example.domain.Engineer;
import com.example.domain.Manager;
import com.example.domain.Admin;
import com.example.domain.Director;
import java.text.NumberFormat;
public class EmployeeTest {
public static void main(String[] args) {
// Create the classes as per the practice
Engineer eng = new Engineer(101, "Jane Smith", "012-34-5678", 120_345.27);
Manager mgr = new Manager(207, "Barbara Johnson", "054-12-2367", 109_501.36, "US Marketing");
Admin adm = new Admin(304, "Bill Munroe", "108-23-6509", 75_002.34);
Director dir = new Director(12, "Susan Wheeler", "099-45-2340", 120_567.36, "Global Marketing", 1_000_000.00);
// Print information about the objects you created
printEmployee(eng);
printEmployee(adm);
printEmployee(mgr);
printEmployee(mgr1);
printEmployee(dir);
System.out.println("\nTesting raiseSalary and setName on Manager:");
mgr.setName ("Barbara Johnson-Smythe");
mgr.raiseSalary(10_000.00);
printEmployee(mgr);
}
public static void printEmployee(Employee emp) {
System.out.println(); // Print a blank line as a separator
// Print out the data in this Employee object
System.out.println("Employee id: " + emp.getEmpId());
System.out.println("Employee name: " + emp.getName());
System.out.println("Employee Soc Sec #: " + emp.getSsn());
System.out.println("Employee salary: " + NumberFormat.getCurrencyInstance().format((double) emp.getSalary()));
}
}
How can I edit according to the given question
Manager.java
package com.example.domain;
public class Manager extends Employee {
private String deptName;
public Manager(int empId, String name, String ssn, double salary, String deptName) {
super(empId, name, ssn, salary);
this.deptName = deptName;
}
public String getDeptName() {
return deptName;
}
}

You can just add an array as follows:
public class Manager extends Employee {
private String deptName;
private List<Employee> employees = new ArrayList<Employee>();
public void addEmployee(Employee someone){
employees.add(someone);
}
and then in your main code, just add them.
manager.addEmployee(someone);

Here is an example using an ArrayList instead of an Array. ArrayLists are good for situations like this, as they are dynamic (you don't have to set a specific size) and they have built in functions for adding and removing without having to shift all of the existing employees up or down the line.
package com.example.domain;
public class Manager extends Employee {
private String deptName;
ArrayList<Employee> employees = new ArrayList<Employee>();
public Manager(int empId, String name, String ssn, double salary, String deptName) {
super(empId, name, ssn, salary);
this.deptName = deptName;
}
public String getDeptName() {
return deptName;
}
public void add(Employee e) {
employees.add(e);
}
public void remove(Employee e) {
employees.remove(e);
}

Use the ArrayList to have the list of Employee object. And it is good practice to have the null check before add an object to the list.
package com.test;
import java.util.ArrayList;
import java.util.List;
public class Manager extends Employee {
private String deptName;
private List<Employee> empList = new ArrayList<Employee>();
public Manager(int empId, String name, String ssn, double salary,
String deptName) {
super(empId, name, ssn, salary);
this.deptName = deptName;
}
public String getDeptName() {
return deptName;
}
public void addEmployee(Employee employee) {
if (employee != null) {
empList.add(employee);
}
}
public boolean removeEmployee(Employee employee) {
return empList.remove(employee);
}
}

It looks like you have your manager class. You could create an ArrayList to store of type Employee and use code such as below to remove it. Alternatively from an int to remove it you could use the ID, Name, or other variations. Hopefully this is somewhat helpful to you or can get you going in the right direction.
` public void removeEmployee(Employee emp, int position) {
this.empArray.remove(position);
System.out.println("Employee was deleted.");
}`
public void addEmployee(Employee emp) {
this.empArray.add(emp);
System.out.println("Employee was Added.");
}

Use arrayList of Employees
ArrayList<Employee> employees = new ArrayList<Employee>();
empolyees.add(employee);

Related

Add student to student ArrayList (java)

Before you read ahead, this is for my homework so the questions/answers are going to be specific.
I am writing some code that takes a student's name and adds it to the student ArrayList. I have a class for students and another class for a course (the course is where the add student and the ArrayList is ). The problem that I am having is that the code is restricting me from using some methods of the student class even though I have used them before. Also, the newly created student has to return the reference of the student, and if it fails it will return null. I have tried that but it has given me errors and I am unsure on how to incorporate the if-else function within the method.
Below is my code for the student class:
public class Student {
// instance fields
//class implementation
private String name;
private String surname;
private long studentId;
private String loginId;
private static int count = 10000001;
private double[] quizMarks; //declare as an array
//constuctors
public Student(String name, String surname) {
this.name = name;
this.surname = surname;
this.studentId = studentId;
quizMarks = new double[0];//initialize array
}
//accessors and mutator methods
//set student's name and surname. Changing student's name does not affect the students' loginID
public void Name(String name, String surname) {
}
//returns name and surname separated by comma (name, surname)
public String setName() {
return name + ", " + surname;
}
}
class for Course:
import java.util.ArrayList;
public class Course{
private ArrayList<Student> students;
ArrayList<Double> quiz;
public Course() {
students = new ArrayList<Student>();
quiz = new ArrayList<Double>();
}
Student addStudent (String name, String familyName){
students.add(setName(Name(name, familyName)));
return null;
}
Student deleteStudent(long studentId){
students.remove(studentId);
return null;
}
}
}
This,
students.add(setName(Name(name, familyName)));
is not correct. You don't want to add a String to stduents you want a Student. Like,
students.add(new Student(name, familyName));
import java.util.ArrayList;
public class Course{
// variables and constructors
Student addStudent (String name, String familyName){
students.setName(name, familyName);
return null;
}
Student deleteStudent(long studentId){
students.remove(studentId);
return null;
}
}
}
There exists no Add or remove method in class Student so either you can add them in your format or correct that format.
public class Student {
// variables
// constuctors
public Student(String name, String surname) {
this.name = name;
this.surname = surname;
this.studentId = studentId;
quizMarks = new double[0];//initialize array
}
public Student remove(Student obj) {
obj = null; //Destroying the reference
}
public void Name(String name, String surname) {
}
//returns name and surname separated by comma (name, surname)
public String setName() {
return name + ", " + surname;
}
}

Inheritance and arrays in Java

I have a class look like this:
public class People {
private String Name;
private String Address;
public People(String aName, String aAddress) {
this.Name=aName;
this.Address=aAddress;
}
public String getName() {
return Name;
}
public String getAddress() {
return Address;
}
void display() {
System.out.println("Name:\t"+Name);
System.out.println("Address:\t" +Address);
}
}
and another 2:
class Students extends People{
private int MatriculationNumber;
private String CourseName;
public Students (String aName, String aAddress, int matriculationNumber, String courseName){
super(aName,aAddress);
this.MatriculationNumber=matriculationNumber;
this.CourseName=courseName;
}
void display() {
super.display();
System.out.println("Matriculation Number: \t" +MatriculationNumber);
System.out.println("Course Name: \t" +CourseName);
}
}
class Staffs extends People{
private int EmployeeNumber;
private String Department;
public Staffs (String aName, String aAddress, int employeeNumber, String department){
super(aName,aAddress);
this.EmployeeNumber=employeeNumber;
this.Department=department;
}
void display() {
super.display();
System.out.println("Employee Number: \t" +EmployeeNumber);
System.out.println("Department: \t" +Department);
}
}
The question is how to create a class named "School" which have a List can contain both Students and Staffs, so I can add a method like AddPeople() which can add or remove Students or Staffs from it?
You can use the below solution. The solution is not thread-safe but should work fine for your usecase.
import java.util.ArrayList;
class School {
private List<People> peopleList = new ArrayList<People>();
public void addPeople(People people) {
peopleList.add(people);
}
public void removePeople(People people) {
peopleList.remove(people);
}
public static void main(String... args) {
Student student = new Student("Name", "Address", 90, "Course");
Staff staff = new Staff("Name", "Address", 1001, "Department");
School school = new School();
school.addPeople(student);
school.addPeople(staff);
school.removePeople(student);
school.removePeople(staff);
}
}
You can create a new Staff Class which also extends from the People Class
package so;
public class Staff extends People {
public Staff(String aName,String aAddress) {
super(aName, aAddress);
}
}
Then give as type of your list the base class People.
package so;
import java.util.ArrayList;
import java.util.List;
public class School {
List<People> peopleContainer = new ArrayList<People>();
public void addPeople(People p){
this.peopleContainer.add(p);
}
public void removePeople(People p) {
this.peopleContainer.remove(p);
}
public void displayPeople() {
for(People person : peopleContainer) {
person.display();
}
}
}
Then you can add staff and student objects to your list and also all other objects which classes extends from people or even people objects itself.
package so;
public class Main {
public static void main(String[] args) {
Students stud1 = new Students("Max", "MustermanAddress", 181242, "CS50");
Staff staff1 = new Staff("Christian", "AugustAddress");
School school = new School();
school.addPeople(stud1);
school.addPeople(staff1);
school.displayPeople();
school.removePeople(staff1);
System.out.println();
System.out.println();
school.displayPeople();
}
}
Output will be
Name: Max
Address: MustermanAddress
Matriculation Number: 181242
Course Name: CS50
Name: Christian
Address: AugustAddress
Name: Max
Address: MustermanAddress
Matriculation Number: 181242
Course Name: CS50

Adding elements to an ArrayList from another class

I just have this basic code where I need help adding employee data to an ArrayList of another class. I am just writing this code in preparation for an assignment, so don't bash my code too much. Essentially though, i'll be needing to add elements of employees and delete them eventually. But for now, I just need help adding the elements to my other Employee class. =]
public class main {
private static Employee employee;
public static void main(String[] args) {
employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
...............
import java.util.ArrayList;
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> Employee = new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
}
Simple Example -
package com;
import java.util.ArrayList;
public class TestPage{
public static void main(String[] args){
Employee emp1, emp2;
emp1 = new Employee();
emp2 = new Employee();
emp1.setName("MAK");
emp2.setName("MICHELE");
emp1.setAddress("NY");
emp2.setAddress("WY");
//and keep putting other information like this
ArrayList<Employee> employee = new ArrayList<Employee>();
employee.add(emp1);
employee.add(emp2);
System.out.println("emp1 name is : " + employee.get(0).getName());
System.out.println("emp2 name is : " + employee.get(1).getName());
System.out.println("emp1 address is : " + employee.get(0).getAddress());
System.out.println("emp2 address is : " + employee.get(1).getAddress());
}
}
class Employee{
String name, address;
int age, salary;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
It seems like what you're asking is based on one employee having sub-employees and that structurally that probably represents a hierarchy (Some commenters seem to be missing that point). But that's an assumption on my part. Based on that assumption.
A little bit of feedback to start on structure of your main class:
public class main {
public static void main(String[] args) {
Employee employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
It seems to me that there's no reason to have a static instance variable for that root employee instance. You should try to limit the scope of variables where possible. It seems like it could very well be in the main() method's scope.
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> employees= new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
public ArrayList<Employee> getEmployees() {
return this.employees;
}
}
It may be better to name your arraylist employees or employeeList. I went with employees in this case because that convention is preferable.
And in relation to your question, ArrayList is pass by reference so you could just add a getter method for the sub-employee list (employees).
To add employees from your main method you could do something like
Employee rootEmployee = new Employee(5, 10.0);
rootEmployee.getEmployees().add(new Employee(6, 5.0));
Or you could add an additional method to Employee like this:
public void addEmployee(Employee e) {
employees.add(e);
}

Efficiently sort a list of objects that logically are part of the same entity

I have a series of objects that I want to sort in a specific way.
Example:
I have the class Employee that has an attribute departmentId.
So many instances of Employee objects have the same value for departmentId.
An employee also has a salary attribute.
So I have a List<Employee> employees objects that I want to sort so that the sorting order is as follows:
The employee with the lowest salary is first in the list followed by all the other employees sorted by salary of the same department.
Then after the last employee of that department I want the next department who has an employee with less salary than all other departments and the rest of the employees sorted etc.
E.g.
(John, 10000, A)
(Jane, 30000, A)
(Bill, 32000, A)
(Jim, 12000, B)
(Jake, 50000, B)
(James, 14000, C)
etc
What is the most efficient way to accomplish this? I want to make the code as compact and efficient as possible rather than creating temporary anonymous classes to add them to hash maps (unless that is the only efficient way).
Note:
I know about comparators and comparable etc.
My question is not about how to actually do the sorting (I know implement comparator) but how can code like this be efficiently done preferably avoiding a bunch of temporary anonymous objects
Also: I am not using Java 8 and would like a plain Java approach
Update:
In response to comments. I want the department with the lowest salary first then the next highest etc
Personally I'd use an Employee class and Department class, both would extend the Comparable<T> interface to make use of library functionality.
Here is an example of a Department class which has a name and a list of employees, which are sorted upon construction. You may want to shallow-copy the list on getEmployees() to prevent others from altering it's order:
class Department implements Comparable<Department> {
private List<Employee> employees;
private char name;
public Department(char name, List<Employee> employees) {
// avoid mutating original list
this.employees = new ArrayList<Employee>(employees);
this.name = name;
Collections.sort(this.employees);
}
#Override
public int compareTo(Department other) {
if (other == null) {
return 1;
}
// employees are sorted by salary within their department.
// all we need is to compare the lowest-salary employees
// from both departments
return this.employees.get(0).getSalary()
- other.employees.get(0).getSalary();
}
public List<Employee> getEmployees() {
return this.employees;
}
public char getName() {
return this.name;
}
}
Now Employee class only has to implement compareTo(Employee other) with the salary comparison:
class Employee implements Comparable<Employee> {
private String name;
private int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
#Override
public int compareTo(Employee other) {
if (other == null) {
return 1;
}
return this.salary - other.salary;
}
#Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + "]";
}
public String getName() {
return name;
}
public int getSalary() {
return salary;
}
}
This should allow you to use Collections.sort on lists of departments and get the right order. Here is a full blown example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Fiddles {
static class Department implements Comparable<Department> {
private List<Employee> employees;
private char name;
public Department(char name, List<Employee> employees) {
// avoid mutating original list
this.employees = new ArrayList<Employee>(employees);
this.name = name;
Collections.sort(this.employees);
}
#Override
public int compareTo(Department other) {
if (other == null) {
return 1;
}
return this.employees.get(0).getSalary()
- other.employees.get(0).getSalary();
}
public List<Employee> getEmployees() {
return this.employees;
}
public char getName() {
return this.name;
}
}
static class Employee implements Comparable<Employee> {
private String name;
private int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
#Override
public int compareTo(Employee other) {
if (other == null) {
return 1;
}
return this.salary - other.salary;
}
#Override
public String toString() {
return "Employee [name=" + name + ", salary=" + salary + "]";
}
public String getName() {
return name;
}
public int getSalary() {
return salary;
}
}
public static void main(String args[]) {
final Department A = new Department('A', new ArrayList<Employee>() {
{
add(new Employee("John", 10000));
add(new Employee("Jane", 30000));
add(new Employee("Bill", 32000));
}
});
final Department B = new Department('B', new ArrayList<Employee>() {
{
add(new Employee("Jim", 12000));
add(new Employee("Jake", 50000));
}
});
final Department C = new Department('C', new ArrayList<Employee>() {
{
add(new Employee("James", 14000));
}
});
List<Department> departments = new ArrayList<Department>() {
{
add(A);
add(B);
add(C);
}
};
Collections.shuffle(departments);
Collections.sort(departments);
for (Department department : departments) {
for (Employee e : department.getEmployees()) {
System.out.println(String.format(
"Employee: %s, Salary: %d, department: %s",
e.getName(), e.getSalary(), department.getName()));
}
}
}
}
I believe the simplest way is to:
Prepare a Map from each department ID to the minimum salary in that department. This requires scanning once through the list (O(n)).
Make a comparator that uses that map. It's just a single object. The comparator sorts such that:
If two employees are in the same department, compare their salaries.
If the two departments are different, compare their minimum salaries based on the above map.
If they have the same rank (lowest salary), sort by their IDs (otherwise you might get two departments with the same lowest salary mixed).
Otherwise compare their ranks.
So here is a demonstration (Edit: the operations are now encapsulated in the Employee class. The work it does is the same, though):
public class Employee {
private String name;
private int salary;
private String department;
/**
* Comparator - Note that it has a constructor that takes a department ranking
* list, which should be prepared in advance
*/
private static class DepartmentAndSalaryComparator implements Comparator<Employee>{
Map<String,Integer> departmentRanking;
public DepartmentAndSalaryComparator(Map<String,Integer> departmentRanking) {
this.departmentRanking = departmentRanking;
}
#Override
public int compare(Employee o1, Employee o2) {
// If employees belong to the same department, rank them by salary
if ( o1.department.equals(o2.department )) {
return o1.salary - o2.salary;
}
// Get the lowest salaries for the departments of the respective employees
int o1Rank = departmentRanking.get(o1.department);
int o2Rank = departmentRanking.get(o2.department);
if ( o1Rank == o2Rank ) {
return o1.department.compareTo(o2.department);
}
return o1Rank - o2Rank;
}
}
public Employee(String name, int salary, String department) {
this.name = name;
this.salary = salary;
this.department = department;
}
/**
* Creates a map of department id to minimum salary in that department
* from a given list of employees.
* This operation is O(n)
* #param employees List of employees for which to calculate map
* #return Map of department rankings
*/
private static Map<String,Integer> calculateDepartmentRanking( List<Employee> employees ) {
Map<String,Integer> rankings = new HashMap<>();
for ( Employee emp : employees ) {
Integer currMin = rankings.get(emp.department);
if ( currMin == null || currMin > emp.salary ) {
rankings.put(emp.department, emp.salary);
}
}
return rankings;
}
/**
* Static method to sort a list of employees by Department, then by Salary, where
* the order of department is based on the minimum salary in that department.
* This operation is O(n log n)
*
* #param employees The list of employees to sort
*/
public static void sortListBySalaryBasedDepartment( List<Employee> employees ) {
Collections.sort(employees, new DepartmentAndSalaryComparator(calculateDepartmentRanking(employees)));
}
#Override
public String toString() {
return String.format("Employee: name=%s, salary=%d, dept.=%s",
name,
salary,
department);
}
public static void main(String[] args) {
// Create example list and shuffle it to make sure it's not ordered
List<Employee> employees = Arrays.asList(
new Employee("Millie", 12000, "Accounts"),
new Employee("Morris", 21200, "Accounts"),
new Employee("Jerry", 22000, "Accounts"),
new Employee("Ellen", 17000, "Sales"),
new Employee("Sandy", 12500, "Technology"),
new Employee("Jack", 40000, "Technology")
);
Collections.shuffle(employees);
// Sort using the special comparator
Employee.sortListBySalaryBasedDepartment(employees);
for (Employee e : employees) {
System.out.println(e);
}
}
}
Output:
Employee: name=Millie, salary=12000, dept.=Accounts
Employee: name=Morris, salary=21200, dept.=Accounts
Employee: name=Jerry, salary=22000, dept.=Accounts
Employee: name=Sandy, salary=12500, dept.=Technology
Employee: name=Jack, salary=40000, dept.=Technology
Employee: name=Ellen, salary=17000, dept.=Sales

Edit Method for Hashmap EmployeeStore

I am making an EmployeeStore that will store names, dob, id, email address etc... and i need to write an edit method. I have googled and i cannot find how to do this can anyone help? Here is my code:
//Imports.
import java.util.Scanner;
//********************************************************************
public class MainApp
{
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
new MainApp().start();
}
public void start()
{
EmployeeStore Store = new EmployeeStore();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
//Test Code with the new Hashmap.
/*Store.print();
Store.clear();
Store.print();
Store.add(new Employee ("James O' Carroll", 18,"hotmail.com"));
Store.add(new Employee ("Andy Carroll", 1171,"yahoo.com"));
Store.add(new Employee ("Luis Suarez", 7,"gmail.com"));
Store.print();
Store.remove("Andy Carroll");
Store.print();*/
//********************************************************************
//Switch Statement for use of a menu.
int choice;
do {
choice = getMenuChoice("1.\tLibrarian\n2.\tPublic User\n3.\tExit\n\n", 3, "Please enter choice:", "Error [1,3] only");
switch (choice) {
case 1:
System.out.println("Librarian Functionality...\n");
break;
case 2:
System.out.println("Public User functionality...\n");
break;
case 3:
System.out.println("Program Finished");
}
}
while (choice != 3);
}
//********************************************************************
public static int getMenuChoice(String menuString, int limit, String prompt, String errorMessage)
{
System.out.println(menuString);
int choice = inputAndValidateInt(1, limit, prompt, errorMessage);
return choice;
}
//********************************************************************
public static int inputAndValidateInt(int min, int max, String prompt, String errorMessage) {
int number;
boolean valid;
do {
System.out.print(prompt);
number = keyboard.nextInt();
valid = number <= max && number >= min;
if (!valid) {
System.out.println(errorMessage);
}
} while (!valid);
return number;
}
//********************************************************************
}
//Imports:
//********************************************************************
//Employee Class.
public class Employee
{
//Variables.
private String employeeName;
private int employeeId;
private String employeeEmail;
//********************************************************************
//Constructor.
public Employee(String employeeName, int employeeId, String employeeEmail)
{
this.employeeName = employeeName;
this.employeeId = employeeId;
this.employeeEmail = employeeEmail;
}
//********************************************************************
//Getters.
public String getEmployeeEmail() {
return employeeEmail;
}
public void setEmployeeEmail(String employeeEmail) {
this.employeeEmail = employeeEmail;
}
public String getEmployeeName() {
return employeeName;
}
public int getEmployeeId() {
return employeeId;
}
//********************************************************************
//toString method.
public String toString() {
return "Employee [employeeName=" + employeeName + ", employeeId="
+ employeeId + ", employeeEmail=" + employeeEmail + "]";
}
//********************************************************************
}
//Imports.
import java.util.HashMap;
//********************************************************************
import java.util.Map;
public class EmployeeStore
{
HashMap<String, Employee> map;
//Constructor.
public EmployeeStore()
{
map = new HashMap<String,Employee>();
}
//********************************************************************
//Hashmap Methods.
//Add to the Hashmap : Employee.
public void add(Employee obj)
{
map.put(obj.getEmployeeName(), obj);
}
//********************************************************************
//Remove from the Hashmap : Employee.
public void remove(String key)
{
//Remove the Employee by name.
map.remove(key);
}
//********************************************************************
//Clear the Hashmap : Employee.
public void clear()
{
map.clear();
}
//********************************************************************
//Print the Hashmap : Employee.
public void print()
{
System.out.println("\n********Employee's in the Company.********");
for (Employee employee : map.values())
{
System.out.println("Employee Name:\t" + employee.getEmployeeName());
System.out.println("Employee Id:\t" + employee.getEmployeeId());
System.out.println("E-mail:\t"+ employee.getEmployeeEmail());
}
}
//********************************************************************
//********************************************************************
}
You'll need to fetch the Employee object from the HashMap, then modify the object. For example, to change the email:
//in class EmployeeStore
String email = somehowGetNewEmail();
Employee toEdit = map.get(somehowGetName());
toEdit.setEmail(email)
Alternately:
//in EmployeeStore
public Employee get(String name){
return map.get(name);
}
//in any class with reference to an EmployeeStore "store"
store.get(name).editSomething(something);
A HashMap stores references to objects. That means when you read ("get") an object from a HashMap and make changes to its attributes, the changes will be carried over without you having to write it back to the HashMap.
So all your edit method has to do is call map.get(name) and make the changes to the returned Employee object. Note that you can not change the key of the HashMap that way. In order to "rename" an employee, you have to remove the value of the old key from the hash map and insert it under a new key.

Categories