PR2/Lernen/CloneMitArrayList.java

71 lines
2.2 KiB
Java

package Lernen;
import java.util.ArrayList;
import Testat1.Tutor_Aufgaben.Clone.Raumanzug;
class Person1 implements Cloneable {
private String name;
private ArrayList<String> hobbies;
private Raumanzug raumanzug;
public Person1(String name, ArrayList<String> hobbies, Raumanzug raumanzug) {
this.name = name;
this.hobbies = hobbies;
this.raumanzug = raumanzug;
}
// Override clone method to provide deep copy
@Override
public Object clone() throws CloneNotSupportedException {
Person1 cloned = (Person1) super.clone();
// Deep copy the ArrayList
cloned.hobbies = (ArrayList<String>) this.hobbies.clone();
cloned.raumanzug = (Raumanzug) this.raumanzug.clone();
return cloned;
}
public ArrayList<String> getHobbies(){
return hobbies;
}
public Raumanzug getAnzug() {
return raumanzug;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", hobbies=" + hobbies +
'}';
}
}
public class CloneMitArrayList {
public static void main(String[] args) {
ArrayList<String> hobbies = new ArrayList<>();
hobbies.add("Reading");
hobbies.add("Swimming");
Person1 original = new Person1("Alice", hobbies, new Raumanzug(new Person("amin", "samin", 33)));
try {
Person1 cloned = (Person1) original.clone();
// Modify the hobbies list in the cloned object
cloned.getHobbies().add("Hiking");
cloned.getAnzug().setSauerstoffVorrat(3.0);
cloned.getAnzug().getPerson().setName("samir");
System.out.println("Original: " + original);
System.out.println(original.getAnzug().getSauerstoffVorrat());
System.out.println(original.getAnzug().getPerson().getName());
System.out.println("Cloned: " + cloned);
System.out.println(cloned.getAnzug().getSauerstoffVorrat());
System.out.println(cloned.getAnzug().getPerson().getName());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}