Lets say, Employee
class has three properties.
class Employee {
int id;
String name;
String team;
public Employee(){
this.id = id;
this.name = name;
this.team = team;
}
}
I want to remove team
from the object before putting into HashMap
.
Map<Integer, Employee> empMap = new HashMap<>();
Employee e1 = new Employee(100, "John", "Dev");
Employee e2 = new Employee(101, "Mary", "Dev");
Employee e3 = new Employee(103, "Andy", "QA");
empMap.put(e1.getId(), e1);
empMap.put(e2.getId(), e2);
empMap.put(e1.getId(), e3);
The values in empMap
shouldn't have team
property in it. Creating new objects would work but it is costly in real time. Is there a way to achieve this without creating new objects.
One option, as you have mentioned, is to create new objects without the team property. Another is to use a façade
public class MapEmpFacade extends Employee {
public MapEmpFacade(Employee emp) {
//define all methods to return the method results from emp, except for getTeam
}
public int getTeam() { return null; } //override getTeam
}
You may review your design to be sure you need the property to be there. You are holding Employee
references in the map
, the team
property is there and probably is correctly representing an Employee
... you can just avoid using the team
property ... or maybe you want to have a Person
class.
If you are using those instances from some framework to do something (eg: serialization, persistence, etc) it should probably provide a way to ignore/skip a property in your object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.