Last active
October 13, 2021 16:57
-
-
Save codinko/42fa0c71b3eb039ad08b79accc631f6c to your computer and use it in GitHub Desktop.
immutable-deepcopy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Java Program to Create An Immutable Class | |
import java.util.HashMap; | |
import java.util.Map; | |
final class Student { | |
private final String name; | |
private final int rollNo; | |
private final Map<String, String> map1; | |
public Student(String name, int rollNo, Map<String, String> map1) | |
{ | |
this.name = name; | |
this.rollNo = rollNo; | |
Map<String, String> tempMap = new HashMap<>(); | |
for (Map.Entry<String, String> entry : | |
metadata.entrySet()) { | |
tempMap.put(entry.getKey(), entry.getValue()); | |
} | |
this.map1 = tempMap; | |
} | |
public String getName() { return name; } | |
public int getRollNo() { return rollNo; } | |
// Note that there should not be any setters | |
public Map<String, String> getMap1() | |
{ | |
// Creating Map with HashMap reference | |
Map<String, String> tempMap = new HashMap<>(); | |
for (Map.Entry<String, String> entry : | |
this.map1.entrySet()) { | |
tempMap.put(entry.getKey(), entry.getValue()); | |
} | |
return tempMap; | |
} | |
} | |
class Main1 { | |
public static void main(String[] args) | |
{ | |
Map<String, String> map = new HashMap<>(); | |
map.put("1", "first"); | |
map.put("2", "second"); | |
Student s = new Student("John", 101, map); | |
System.out.println(s.getName()); | |
System.out.println(s.getRollNo()); | |
System.out.println(s.getMap1()); | |
map.put("3", "third"); // Remains unchanged due to deep copy in constructor | |
System.out.println(s.getMap1()); | |
s.getMap1().put("4", "fourth"); // Remains unchanged due to deep copy in getter | |
System.out.println(s.getMap1()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment