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 01:38] 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.List;
 +
 final class Record { final class Record {
  
-  private final long id; +    private final long id; 
-  private final String name; +    private final String name; 
-  private final List<String> tokens;+    private final List<String> tokens;
  
-  public Record(long id, String name, List<String> tokens) { +    public Record(long id, String name, List<String> tokens) { 
-    this.id = id; +        this.id = id; 
-    this.name = name; +        this.name = name;
-    this.tokens = tokens; +
-  }+
  
-  public long getId() { +        /*  This works, but: 
-    return id; +         - it will always duplicate elements 
-  }+         - the same copy should be used also in getTokens() method. 
 +        */ 
 +        //this.tokens = new ArrayList<>(tokens);
  
-  public String getName() { +        /*  If tokens is already unmodifiable (for ex. was formed using List.of), 
-    return name+            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)
 +    }
  
-  public List<String> getTokens() { +    public long getId() { 
-    return new ArrayList<>(tokens)+        return id
-  }+    }
  
-  @Override +    public String getName() { 
-  public String toString() { +        return name; 
-    return "Record{" + +    
-        "id=" + id + + 
-        ", name='" + name + '\'' + +    /** 
-        ", tokens=" + tokens + +     * 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<String> getTokens() { 
 +        //return new ArrayList<>(tokens); 
 +        return tokens; 
 +    } 
 + 
 +    @Override 
 +    public String toString() { 
 +        return "Record (id = " + id + ", name='" + name + '\'' + ", tokens=" + tokens + ")"
 +    }
 } }
-</code> 
  
 +class TestRecord {
  
 +    public static void main(String[] args) {
 +        List<String> tokens = new ArrayList<>();
 +        tokens.add("Token 1");
 +        tokens.add("Token 2");
 +
 +        Record record = new Record(1, "One", tokens);
 +        System.out.println(record);
 +
 +        tokens.remove(0);
 +        System.out.println(record);
 +
 +        System.out.println(record.withName("Two"));
 +
 +        record.getTokens().add("Token 3");
 +        System.out.println(record);
 +
 +    }
 +}
 +</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>
  
 +===== Immutable classes in JDK =====
 +Some immutable classes from java api:
 +  * java.lang.String
 +  * java.lang.Integer
 +  * java.io.File
 +  * java.util.Locale
 +  * java.awt.Font
 +  * java.net.InetSocketAddress
  
 +<note tip>
 +Immutable classes can also be created using builder pattern. 
 +Builder Pattern is a better option if the immutable class has a lot of attributes and some of them are optional.</note>
  
java/immutable-objects.txt · Last modified: 2023/07/04 19:36 by 127.0.0.1