1

The below return statement gives me a Sonar security warning even when I am not returning the original array but a clone of it.

What is the "correct" way to do this?

public String[] getList() {
        return list!=null? list.clone():null;
}
nrainer
  • 2,542
  • 2
  • 23
  • 35
ashish p
  • 202
  • 3
  • 10

1 Answers1

0

Edited my previous answer for some obvious errors :)

List.clone() doesn't work because it returns a shallow copy of the list. So basically it just returns the reference to the original list. We don't want that here. What we want is a brand new array that doesn't have the same reference to be returned. For that the best idea will always be to create a new array and run a for loop like this:

String[] newArr = new String[list.length];
int i = 0;
for (String s : list) {
    newArr[i++] = s
}

If you wanna know why this is the issue, refer to this answer :)

Tejas Shetty
  • 162
  • 2
  • 9
nrainer
  • 2,542
  • 2
  • 23
  • 35