User Tools

Site Tools


java:immutable-objects

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Last revisionBoth sides next revision
java:immutable-objects [2023/04/08 02:26] odeftajava:immutable-objects [2023/04/08 02:38] odefta
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 works, but it will always duplicate elements */+ 
 +        /*  This works, but
 +         it will always duplicate elements 
 +         - the same copy should be used also in getTokens() method. 
 +        */
         //this.tokens = new ArrayList<>(tokens);         //this.tokens = new ArrayList<>(tokens);
 +
         /*  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<String> getTokens() {     public List<String> getTokens() {
 +        //return new ArrayList<>(tokens);
         return tokens;         return tokens;
     }     }
Line 68: Line 75:
     @Override     @Override
     public String toString() {     public String toString() {
-        return "Record (id = " + id + ", name='" + name + '\'' + ", tokens=" + tokens + ')';+        return "Record (id = " + id + ", name='" + name + '\'' + ", tokens=" + tokens + ")";
     }     }
 } }
Line 92: Line 99:
     }     }
 } }
 +</code>
 +Output:
 +<code>
 +Record (id = 1, name='One', tokens=[Token 1, Token 2])
 +Record (id = 1, name='One', tokens=[Token 1, Token 2])
 +Record (id = 1, name='Two', tokens=[Token 1, Token 2])
 +Exception in thread "main" java.lang.UnsupportedOperationException
 + at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:71)
 + at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:75)
 + at ro.medjava.immutability.TestRecord.main(Record.java:65)
 </code> </code>
  
java/immutable-objects.txt · Last modified: 2023/07/04 19:36 by 127.0.0.1