Reputation: 885
I have refered : Security - Array is stored directly.
My code is as
public IndexBlockAdapter(String[] itemStr) {
if(itemStr == null) {
this.itemStr = new String[0];
} else {
this.itemStr = Arrays.copyOf(itemStr, itemStr.length);
}
}
But Sonar still picks it up and complains about "Array is stored directly", despite making a copy. I am very confused.
Any help is appreciated!
Upvotes: 0
Views: 5228
Reputation: 5118
This should work for you
public IndexBlockAdapter(String[] newItemStr) {
if(newItemStr == null) {
this.itemStr = new String[0];
} else {
this.itemStr = Arrays.copyOf(newItemStr, newItemStr.length);
}
}
Upvotes: 0
Reputation: 3649
Arrays.copyOf does a shallow copy.
It just copies the references and not the actual values.
The following code will print all true
which proves the fact
String [] str1 = {"1","2","3"};
String [] str2 = Arrays.copyOf(str1, str1.length);
for (int i=0;i<str1.length;i++) {
System.out.println(str1[i] == str2[i]);
}
Instead, if you use the following code, you will do a deep copy, and you should be good
String [] str3 = new String[str1.length];
for (int i=0;i<str1.length;i++) {
str3[i] = new String(str1[i]);
}
for (int i=0;i<str1.length;i++) {
System.out.println(str1[i] == str3[i]);
}
Upvotes: 3