import java.util.Date;
class Person {
private String name;
private Date dob;
public Person(String name, Date dob) {
this.name = name;
this.dob = new Date(dob.getTime()); (1)
}
public String getName() {
return name;
}
public Date getDob() {
return new Date(dob.getTime()); (2)
}
}
Design an Immutable class that has an java.util.Date member
Upasana | May 19, 2019 | 1 min read | 2,273 views | Multithreading and Concurrency
Design an Immutable class that has an java.util.Date member
As we know that java.util.Date is not immutable, we need to make a defensive copy of java.util.Date field while returning a reference to this instance variable.
Let’s create a hypothetical person class that has name and dob as the only two members.
Immutbale Person Class
1 | We are creating a new copy of Date field otherwise reference to dob field may leak |
2 | We are returning defensive copy of Date field instead of directly returning the reference of instance variable. |
Multithreading and Concurrency:
- Java 8 Parallel Stream custom ThreadPool
- Java Concurrency Interview Questions
- ConcurrentModificationException in Java
- What is purpose of Collections.unmodifiableCollection
- Removing elements while iterating over a Java Collection
- ThreadLocal with examples in Java
- What is difference between sleep() and wait() method in Java?
Top articles in this category:
- What is Immutable Class in Java
- How will you increment each element of an Integer array, using parallel operation
- Can the keys in HashMap be mutable
- Can two threads call two different synchronized instance methods of an Object?
- What is AtomicInteger class and how it works internally
- What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
- Diamond Problem of Inheritance in Java 8
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..