Inspectopedia Help

Assignment or return of field with mutable type

Reports return of, or assignment from a method parameter to an array or a mutable type like 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.Date

  • java.util.Calendar

  • java.util.Collection

  • java.util.Map

  • com.google.common.collect.Multimap

  • com.google.common.collect.Table

The quick-fix adds a call to the field's .clone() method.

Example:

class Log { String[] messages; ... String[] getMessages() { return messages; // warning: Return of String[] field 'messages' } }

After the quick-fix is applied:

class Log { String[] messages; ... String[] getMessages() { return messages.clone(); } }

Use the Ignore assignments in and returns from private methods option to ignore assignments and returns in private methods.

Inspection options

Option

Type

Default

Ignore assignments in and returns from private methods

Checkbox

true

Inspection Details

Available in:

IntelliJ IDEA 2023.3, Qodana for JVM 2023.3

Plugin:

Java, 233.SNAPSHOT

Last modified: 13 July 2023