Skip to content

Simple programs to demonstrate holding immutable data in java objects.

Notifications You must be signed in to change notification settings

shubhamv108/java-immutable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

public final class PersonImmutable {

    private final String name;
    private final HashMap<String, String> info;

    private final Address address;

    public PersonImmutable(final String name, final HashMap<String, String> info, final Address address) {
        this.name = name; // String is immutable for security & concurrency.
        this.info = new HashMap<>(info);
        this.address = address.clone();
    }

    public String getName() {
        return name;
    }

    public HashMap<String, String> getInfo() {
        return new HashMap<>(info);
    }

    public Address getAddress() {
        return this.address.clone();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (!(o instanceof PersonImmutable))
            return false;
        PersonImmutable person = (PersonImmutable) o;
        return Objects.equals(name, person.name) &&
               Objects.equals(info, person.info);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, info);
    }

    @Override
    public String toString() {
        return "PersonImmutable[" +
                "name=" + name + ", " +
                "info=" + info + ", " +
                "address=" + address + ']';
    }
}



public record PersonRecord(String name, HashMap<String, String> info, Address address) {

    public PersonRecord(final String name, final HashMap<String, String> info, final Address address) {
        this.name = name; // String is immutable for security & concurrency.
        this.info = new HashMap<>(info);
        this.address = address;
    }

    @Override
    public HashMap<String, String> info() {
        return new HashMap<>(info);
    }

    public Address address() {
        return this.address.clone();
    }
}

About

Simple programs to demonstrate holding immutable data in java objects.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages