java:immutable-objects
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| java:immutable-objects [2023/04/07 23:27] – odefta | java:immutable-objects [2023/07/04 16:36] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 23: | Line 23: | ||
| ===== Example of immutable class ===== | ===== Example of immutable class ===== | ||
| - | |||
| <code java> | <code java> | ||
| import java.util.ArrayList; | import java.util.ArrayList; | ||
| Line 37: | Line 36: | ||
| this.id = id; | this.id = id; | ||
| this.name = name; | this.name = name; | ||
| - | | + | |
| + | | ||
| + | | ||
| + | - the same copy should be used also in getTokens() method. | ||
| + | | ||
| // | // | ||
| + | |||
| /* If tokens is already unmodifiable (for ex. was formed using List.of), | /* If tokens is already unmodifiable (for ex. was formed using List.of), | ||
| then it will not duplicate elements. | then it will not duplicate elements. | ||
| + | Also, it will prevent the tokens to be modified | ||
| + | (it will throw java.lang.UnsupportedOperationException). | ||
| */ | */ | ||
| this.tokens = List.copyOf(tokens); | this.tokens = List.copyOf(tokens); | ||
| Line 63: | Line 69: | ||
| public List< | public List< | ||
| + | //return new ArrayList<> | ||
| return tokens; | return tokens; | ||
| } | } | ||
| Line 68: | Line 75: | ||
| @Override | @Override | ||
| public String toString() { | public String toString() { | ||
| - | return " | + | return " |
| } | } | ||
| } | } | ||
java/immutable-objects.1680910038.txt.gz · Last modified: (external edit)
