0

In my program I want to create an immutable object.For example, making an arraylist or map immutable.As we know that we have String I.e an immutable object, similarly I want to create my own immutable object.

Rantu
  • 21
  • 1
  • 1
  • 2
  • Ok, so do it. What's the problem? What are you having a hard time with? – Sotirios Delimanolis Apr 11 '14 at 03:57
  • 1
    possible duplicate of [How to create immutable objects in Java?](http://stackoverflow.com/questions/6305752/how-to-create-immutable-objects-in-java) and [Make immutable Java object](http://stackoverflow.com/questions/18194139/make-immutable-java-object) – Baby Apr 11 '14 at 03:59
  • For immutable maps or lists take a look at `Lists.unmodifiableList(...)` and `Maps.unmodifiableMap(...)`. – Mordechai Apr 11 '14 at 05:17

2 Answers2

1

Immutable just means that the value of the object cannot be changed. For instance here is an immutable wrapper around an integer:

public class ImmutableInt {
  private final int value;

  public ImmutableInt(int value) {
    this.value = value;
  }

  public int getValue() {
    return this.value;
  }
}
Aurand
  • 5,487
  • 1
  • 25
  • 35
0

Making an object immutable just means that none of its members can be changed after it's instantiated. You have complete ability to control this in Java by marking instance fields private and final. This forces them to be initialized when the object is instantiated and prevents any further modification after that point.

If you are looking for an easy way to make a Java collection 'immutable', have a look at the java.util.Collections class, which provides static methods that provide read-only wrappers for mutable collections. http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#unmodifiableCollection(java.util.Collection)

DryingPole
  • 31
  • 4