Junior — Senior
Implementation of deep copy of Customer object
livecode
Task condition
The task is to implement the clone() method in the Customer class, which will create a full (deep) copy of the given object.
Requirements:
- The cloned object should not reference the same nested instances (
Address,List<CellNumber>) as the original. - All nested structures within
Customershould be independent copies. - After cloning, the
equals()method should returntrue, but references to nested objects should point to different instances.
package com.jetbulb.interviews;
import java.util.Collections;
import java.util.List;
public class JetbulbInterview {
public static void main(String[] args) {
Customer customer = new Customer(
"123",
66,
new Address(1, "Street"),
Collections.singletonList(new CellNumber("777-555-666", 3.14D))
);
Customer clonedCustomer = customer.clone();
System.out.println(customer.equals(clonedCustomer)); // true
System.out.println(customer == clonedCustomer); // false
System.out.println(customer.address == clonedCustomer.address); // false
System.out.println(customer.number == clonedCustomer.number); // false
}
}
class Customer implements Cloneable {
String id;
int age;
Address address;
List<CellNumber> number;
}
class Address implements Cloneable {
int id;
String name;
}
class CellNumber implements Cloneable {
String number;
double coverage;
}