我对在 HashMap 中填充值有一些问题/疑问
我希望 HashMap 接受“Student”作为键,“Details”作为值。 由于 hashMap 的键应该是不可变的,我有一些疑问,如果
- 学生类(class)不可复制
学生类(class)引用了“实验室”
public class Student { private String id; private String name; private Department dept; public Student(String id, String name, Department dept) { this.id=id; this.name=name; this.dept=dept; } public Department getDepartment() { return this.dept; } } public class Department { private String deptId; private Lab lab; public Department(String deptId, Lab lab) { this.deptId=deptId; this.lab=lab; } public void setLab(Lab lab) { this.lab=lab; } } public class Lab { private String labId; private String labName; public Lab(String labId, String labName) { this.labId=labId; this.labName=labName; } } public class StudentDetails { private String fatherName; private String address public StudentDetails(String fatherName, String address) { this.fatherName=fatherName; this.address=address; } } public class StudentMaintainer { public static void main(String[] args) { StudentDetails stDetails= new StudentDetails("John","Mumbai"); Lab lab= new Lab("100","CS"); Department dept= new Department("900", lab); Student st = new Student("3000",dept); Map<Student,StudentDetails> studentMaintainer= new ArrayList<>(); studentMaintainer.put(st,stDetails); } }
现在即使 Student 是可克隆的,我也可以获取 Department 的引用并调用 setLab() 来更改 StudentObject。 (我错了吗?)
现在如果 Department 和 Lab 来自 3rd party jar,如果 Student hashCode 是 (primeNumber+Student.id+Department.id+Lab.id).hashcode() [只是有些奇怪案例];
最佳答案
据我了解,不可变性与 Cloneable 无关,事实上恰恰相反。不可变性更多地与声明类 final 和使用不可变字段、不可覆盖的方法、无 setter 方法、返回字段或不可变字段的深度副本的 getter 方法等有关...请阅读 A Strategy for Defining Immutable Objects有关更多信息。
您的代码还有一个伪构造函数:
public void Student(String id, String name, Department dept)
{
this.id=id;
this.name=name;
this.dept=dept;
}
一个真正的构造函数不应该被声明为返回任何,甚至不应该是void。更好的做法是:
// note the difference?
public Student(String id, String name, Department dept)
{
this.id=id;
this.name=name;
this.dept=dept;
}
此外,您的 Student 类应该正确地覆盖 equals 和 hashCode,如果它能很好地用作 HashMap 的键的话。
关于java - 如果类没有实现可克隆,我们如何获得不可变对象(immutable对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272831/