Book
# Topic
Constructor
# Problem
Book
Write a class named Book
. It must have three fields: a string field title
, an int field yearOfPublishing
, an array of strings authors
and a constructor to initialize these fields. The order of parameters in the constructor must be the same as presented above.
# Hint & Explain
https://stackoverflow.com/questions/14149733/clone-method-for-java-arrays this article helped me with understanding (a little anyway) on reference and value in arrays and their clones.
If you're running into "The user-supplied array 'authors' is stored directly", you need to make a copy within the object when it gets passed instead of storing it directly. Import
java.utils.Arrays
, then useArrays.copyOf(authors, authors.length)
avoid to store array directly http://geeksforgeekss.blogspot.com/2016/05/sonar-violation-security-array-is.html
# Solution
# Other solution 1
class Book {
String title;
int yearOfPublishing;
String[] authors;
public Book(String title, int yearOfPublishing, String[] authors) {
this.title = title;
this.yearOfPublishing = yearOfPublishing;
this.authors = authors.clone();
}
}
2
3
4
5
6
7
8
9
10
11
# Other solution 2
import java.util.Arrays;
class Book {
String title;
int yearOfPublishing;
String[] authors;
public Book(String title, int yearOfPublishing, String[] authors) {
this.title = title;
this.yearOfPublishing = yearOfPublishing;
if (authors == null) {
this.authors = new String[0];
} else {
this.authors = Arrays.copyOf(authors, authors.length);
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17