Код: Выделить всё
import java.util.*;
public class MyClass {
public static void main(String args[]) throws CloneNotSupportedException {
int[] arr = {1,2,3,4,5,6};
int[] cloned = arr.clone();
System.out.println("Is arr == cloned false?: " + (arr == cloned));
System.out.println("arr's hashcode: " + arr.hashCode());
System.out.println("cloned's hashcode: " + cloned.hashCode());
arr[0] = 99;
System.out.println(Arrays.toString(arr));
System.out.println(Arrays.toString(cloned));
System.out.println("Non-primitive types below: ");
Department hr = new Department(1, "Human Resource");
Employee original = new Employee(1, "Admin", hr);
Employee clonedE = (Employee) original.clone();
System.out.println("Is original == clonedE false?: " + (original == clonedE));
System.out.println("original's hashcode: " + original.hashCode());
System.out.println("clonedE's hashcode: " + clonedE.hashCode());
System.out.println(original.getDepartment().getName());
System.out.println(clonedE.getDepartment().getName());
//Checking shallow and deep copy
clonedE.getDepartment().setName("Finance");
clonedE.setName("CEO");
System.out.println("After modifying Employee name and Department class name");
System.out.println("Original's name: " + original.getName());
System.out.println("Clone's name: " + clonedE.getName());
System.out.println("Original's department name: " + original.getDepartment().getName());
System.out.println("Clone's department name: " + clonedE.getDepartment().getName());
}
}
class Employee implements Cloneable {
private int empoyeeId;
private String employeeName;
private Department department;
public Employee(int id, String name, Department dept)
{
this.empoyeeId = id;
this.employeeName = name;
this.department = dept;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
//Getters and Setters
public Department getDepartment(){
return department;
}
public void setName(String name){
this.employeeName = name;
}
public String getName(){
return employeeName;
}
}
class Department
{
private int id;
private String name;
public Department(int id, String name)
{
this.id = id;
this.name = name;
}
//Getters and Setters
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
Код: Выделить всё
int[] cloned = arr.clone();
Код: Выделить всё
Employee clonedE = (Employee) original.clone();
Обратите внимание, что считается, что все массивы реализуют интерфейс Cloneable и что тип возвращаемого значения метода клонирования типа массива T[] равен T[], где T — любая ссылка или примитив. type.
Мой вопрос заключается в следующем:
- Почему массив clone()< /code> не реализует приведение типов; Почему тип возвращаемого значения метода array clone() — T[]; Какова логика между clone() и универсальным типом?
- Как узнать, когда следует типизировать объект clone()? Является ли функция clone() возвращаемым типом Object?
Подробнее здесь: https://stackoverflow.com/questions/789 ... other-self
Мобильная версия