Collection, Date, Map, Calendar, etc.
Because such types are mutable, this construct may result in unexpected modifications of an object's state from outside the owning class. Although this construct may be useful for performance reasons, it is inherently prone to bugs.
The following mutable types are reported:
java.util.Datejava.util.Calendarjava.util.Collectionjava.util.Mapcom.google.common.collect.Multimapcom.google.common.collect.TableThe quick-fix adds a call to the field's .clone() method for arrays or uses an unmodifiable collection wrapper.
Example:
import java.util.*;
class Log {
private String[] messages = {"one", "two", "three"};
private Map<String, String> map = new HashMap<>();
String[] getMessages() {
return messages; // warning: Return of String[] field 'messages'
}
Map<String, String> mapping() {
return map; // warning: Return of Map<String, String> field 'map'
}
}
After the quick-fix is applied:
import java.util.*;
class Log {
String[] messages = {"one", "two", "three"};
private Map<String, String> map = new HashMap<>();
String[] getMessages() {
return messages.clone();
}
Map<String, String> mapping() {
return Collections.unmodifiableMap(map);
}
}
Use the Ignore assignments in and returns from private methods option to ignore assignments and returns in private methods.