[英]How to create a copy of object of class with map?
I have a class我有一堂课
public class student
{
private int Id;
private map<String , String> subjects;
private map<String , String> teachers;
private String name;
}
Let me explain the scenario more clearly .让我更清楚地解释这个场景。 I have a function which is taking Student object as a parameter .我有一个将 Student 对象作为参数的函数。 This function is being called from various other classes .这个函数是从其他各种类调用的。 Now in this function I am creating seven threads to perform some computation based on the student input object .现在在这个函数中,我创建了七个线程来根据学生输入对象执行一些计算。 Though there is no modification of the student object presently .虽然目前没有修改学生对象。 Still I want to keep it safe by passing in copies of the student object so that if anyone later on modifies the input in any of the threads It should not modify other threads.我仍然想通过传递学生对象的副本来保证它的安全,这样如果以后有人修改了任何线程中的输入,它就不应该修改其他线程。
So how can i create a new object for the map ?那么如何为地图创建一个新对象呢? Also another solution I could try is to create this class as immutable but even then the map is a problem .我可以尝试的另一个解决方案是将此类创建为不可变的,但即使如此,地图也是一个问题。 How to make map immutable .如何使地图不可变。
If the threads have to manipulate the object:如果线程必须操作对象:
Map<String, String> subjects = new HashMap<>()
创建对象和映射的副本,例如使用Map<String, String> subjects = new HashMap<>()
If the threads do not have to manipulate the object:如果线程不必操作对象:
Collections
class为了安全起见,您可以使用Collections
类中的方法使地图不可变By the way:顺便一提:
Subject
objects and Teacher
objects.考虑存储Subject
对象和Teacher
对象的列表。 This makes your code easier to extend, than using maps.这使您的代码比使用地图更容易扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.