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/08 02:16] – odefta | java:immutable-objects [2023/07/04 19: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; | ||
- | | + | |
- | this.tokens = List.copyOf(tokens); //if tokens is already unmodifiable (for ex. came from List.of) it will not duplicate elements. | + | |
+ | | ||
+ | - the same copy should be used also in getTokens() method. | ||
+ | | ||
+ | //this.tokens = new ArrayList<> | ||
+ | |||
+ | | ||
+ | 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); | ||
} | } | ||
Line 47: | Line 57: | ||
public String getName() { | public String getName() { | ||
return name; | return name; | ||
+ | } | ||
+ | |||
+ | /** | ||
+ | * No simple setters, return another copy of the object. | ||
+ | * @param name | ||
+ | * @return Record | ||
+ | */ | ||
+ | public Record withName(String name) { | ||
+ | return new Record(id, name, tokens); | ||
} | } | ||
public List< | public List< | ||
+ | //return new ArrayList<> | ||
return tokens; | return tokens; | ||
} | } | ||
Line 55: | Line 75: | ||
@Override | @Override | ||
public String toString() { | public String toString() { | ||
- | return " | + | return " |
} | } | ||
} | } | ||
Line 70: | Line 90: | ||
tokens.remove(0); | tokens.remove(0); | ||
+ | System.out.println(record); | ||
+ | System.out.println(record.withName(" | ||
+ | |||
+ | record.getTokens().add(" | ||
System.out.println(record); | System.out.println(record); | ||
+ | |||
} | } | ||
} | } | ||
+ | </ | ||
+ | Output: | ||
+ | < | ||
+ | Record (id = 1, name=' | ||
+ | Record (id = 1, name=' | ||
+ | Record (id = 1, name=' | ||
+ | Exception in thread " | ||
+ | at java.base/ | ||
+ | at java.base/ | ||
+ | at ro.medjava.immutability.TestRecord.main(Record.java: | ||
</ | </ | ||
java/immutable-objects.1680909370.txt.gz · Last modified: 2023/07/04 19:36 (external edit)