I have classBook
which can have many Authors
. I pass few objects of class Author
to the constructor of class Book
then copy these objects by Arrays.copyOF
but then if I change any Author
data outside the object it will change everywhere so it means the copy has not been created.
I would like to create deep copy. Code is compiling and running with no errors.
import java.util.Arrays;
public class Book {
private String tytul;
private int rokWydania;
private Author[] autorzy;
public Book(String tytul, int rokWydania, Author... autorzy) {
this.tytul = tytul;
this.rokWydania = rokWydania;
this.autorzy = Arrays.copyOf(autorzy, autorzy.length);
}
public String toString() {
String s = " Tytuł: " + tytul +"\nrok wydania: " + rokWydania + "\n";
if(autorzy.length == 1)
s+=" Autor: " + autorzy[0];
else{
s+=" Autorzy: " + autorzy[0];
for(int i = 1; i < autorzy.length; i++)
s+="\n " + autorzy[i];
}
return s + "\n\n";
}
public static void main(String[] args) {
Author a1 = new Author("Isabel", "Allende", 1942);
Author a2 = new Author("Manueala", "Gretkowska", 1964);
Author a3 = new Author("Piotr", "Pietucha", 1954);
Book b1 = new Book("Suma naszych dni", 2010, a1);
Book b2 = new Book("Polka", 2001, a2);
Book b3 = new Book("Sceny z życia pozamałżeńskiego", 2003, a2, a3);
a2.zmienInformacje("Tove", "Jansson", 1956);
Book b4 = new Book("Lato muminków", 2006, a2);
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println(b4);
}
}
public class Author {
private String imie, nazwisko;
private int rokUrodzenia;
public Author(String imie, String nazwisko, int rokUrodzenia) {
this.imie = imie;
this.nazwisko = nazwisko;
this.rokUrodzenia = rokUrodzenia;
}
public String getImie() {
return imie;
}
public String getNazwisko() {
return nazwisko;
}
public int getRokUrodzenia() {
return rokUrodzenia;
}
@Override
public String toString() {
return imie + " " + nazwisko + " (ur. " + rokUrodzenia + ")";
}
public void zmienInformacje(String imie, String nazwisko, int rokUrodzenia) {
this.imie = imie;
this.nazwisko = nazwisko;
this.rokUrodzenia = rokUrodzenia;
}
}
Desired output:
Tytuł: Suma naszych dni
rok wydania: 2010
Autor: Isabel Allende (ur. 1942)
Tytuł: Polka
rok wydania: 2001
Autor: Manuela Gretkowska (ur. 1964)
Tytuł: Suma naszych dni
rok wydania: 2010
Autorzy: Manuela Gretkowska (ur. 1964)
Piotr Pietucha (ur. 1954)
Tytuł: Lato muminków
rok wydania: 2006
Autor: Tove Jansson (ur. 1956)
My output
Tytuł: Suma naszych dni
rok wydania: 2010
Autor: Isabel Allende (ur. 1942)
Tytuł: Polka
rok wydania: 2001
Autor: Tove Jansson (ur. 1956)//WRONG
Tytuł: Sceny z życia pozamałżeńskiego
rok wydania: 2003
Autorzy: Tove Jansson (ur. 1956)//WRONG
Piotr Pietucha (ur. 1954)
Tytuł: Lato muminków
rok wydania: 2006
Autor: Tove Jansson (ur. 1956)