Immutable class?

How can I make a Java class immutable, what is the need for immutability, and is there any advantage to using this?

+61
java string immutability
Jul 02 2018-10-10T00:
source share
11 answers

What is an immutable object?

An immutable object is one that does not change state after it is created.

How to make an object immutable?

In the general case, an immutable object can be created by defining a class that does not have any of its members and does not have any setters.

The following class will create an immutable object:

class ImmutableInt { private final int value; public ImmutableInt(int i) { value = i; } public int getValue() { return value; } } 

As can be seen from the above example, the value of ImmutableInt can only be set when creating an instance of the object, and if there is only a getter ( getValue ), the state of the object cannot be changed after the instance is created.

However, care must be taken to ensure that all objects referenced by the object must also be immutable, or the state of the object could be changed.

For example, allowing you to get a reference to an array or ArrayList , which will be obtained through a getter, will allow you to change the internal state by changing the array or collection:

 class NotQuiteImmutableList<T> { private final List<T> list; public NotQuiteImmutableList(List<T> list) { // creates a new ArrayList and keeps a reference to it. this.list = new ArrayList(list); } public List<T> getList() { return list; } } 

The problem with the above code is that ArrayList can be obtained using getList and manipulated, which will lead to a change in the state of the object itself, so it is not immutable.

 // notQuiteImmutableList contains "a", "b", "c" List<String> notQuiteImmutableList= new NotQuiteImmutableList(Arrays.asList("a", "b", "c")); // now the list contains "a", "b", "c", "d" -- this list is mutable. notQuiteImmutableList.getList().add("d"); 

One way around this problem is to return a copy of the array or collection when called from the receiver:

 public List<T> getList() { // return a copy of the list so the internal state cannot be altered return new ArrayList(list); } 

What is the advantage of immutability?

The advantage of immutability comes with concurrency. It is difficult to maintain correctness in mutable objects, since several threads may try to change the state of the same object, resulting in some threads seeing a different state of the same object, depending on the time of reading and writing to the said object.

Having an immutable object, we can guarantee that all threads that look at the object will see the same state, since the state of the immutable object will not change.

+109
Jul 02 '10 at 1:10
source share

In addition to the answers already provided, I would recommend reading about immutability in Effective Java, 2nd Ed., As there are some details that are easy to overlook (for example, protective copies). Also effective Java 2nd Ed. is a must for every Java developer.

+13
Jul 02 '10 at 1:20
source share

You make the class immutable as follows:

 public final class Immutable { private final String name; public Immutable(String name) { this.name = name; } public String getName() { return this.name; } // No setter; } 

Immutable classes are useful because they are thread safe. They also express something profound in your design: "Can't change that." When applicable, this is exactly what you need.

+4
Jul 02 '10 at 1:10
source share

Immutable classes cannot override values ​​after it is created. The constructor assigns values ​​to its private variables. Until the object becomes empty, the values ​​cannot be changed due to the inaccessibility of the setter methods.

to be unchanged, must satisfy the following,

  • Al variables must be private .
  • No method mutators (setters).
  • Avoid overriding methods by making the class final (Strong immutability) or methods final (Continuity of the week).
  • A clone is deep if it contains non-primitive or mutable classes.



 /** * Strong immutability - by making class final */ public final class TestImmutablity { // make the variables private private String Name; //assign value when the object created public TestImmutablity(String name) { this.Name = name; } //provide getters to access values public String getName() { return this.Name; } } 

Advanteges: Immutable objects contain their initialized values ​​until they die.

java-immutable-classes-short-note

+3
Aug 02 '14 at 17:30
source share

Q1) What is an immutable class and object?

Ans) An optional class is a class that was once created, its contents cannot be changed. Immutable objects are objects whose state cannot be changed after its creation. e.g. String Class

Q2) How to create an immutable class?

Ans) To create an immutable class, follow these steps:

  • Create the last class.

  • Set property values ​​using only the constructor.

  • Set class properties to final and private

  • Do not provide any settings for these properties.

  • If instance fields include references to mutable objects, do not allow the modification of these objects:

    • Do not provide methods that modify mutable objects.

    • Do not use references to mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies and store links to copies. Similarly, create copies of your internal mutable objects when necessary, to avoid returning originals in your methods.

+3
03 Oct '15 at 11:57
source share

Immutability can be achieved mainly in two ways:

  • using final instance attributes to avoid reassignment
  • using the class interface, which simply does not allow you to perform any operation that can change what is inside your class (only getters and setters

The benefits of immutability are the assumptions you can make at this object:

  • you get the rule of no side effects (which is really popular in functional programming languages) and makes it easier to use objects in a parallel environment, because you know that they cannot be changed in an atomic or non-atomic way when they are used by many threads.
  • a language implementation can handle these objects differently, placing them in memory zones that are used for static data, which makes it possible to use these objects faster and more safely (this is what happens inside the JVM for strings)
+2
Jul 02 '10 at 1:13
source share
  • What is immutable?

In short, the Immutable class is a class whose instances cannot be changed. The information contained in each immutable object is provided at its creation and is frozen throughout its life. When an Immutable object was created, it is read only forever, like a fossil.

  • How to make immutable

    • Make all fields private and final.
    • Do not provide any methods that change the state of objects.
    • Make sure the class cannot be extended.
    • Provide exclusive access to any mutable fields

<strong> Benefits

  • Immutable objects are thread safe, so you won't have any synchronization problems.
  • Immutable objects are good map keys and elements of a set, since these usually do not change after creation.
  • Inevitability simplifies the writing, use and use of code (the class invariant is set once, and then does not change)
  • Inevitability facilitates parallelization of your program, since there are no conflicts between objects.
  • The internal state of your program will be consistent, even if you have exceptions.
  • References to immutable objects can be cached because they are not collected for modification.

As a good programming practice in Java, you should try to use immutable objects as much as possible. Invariability can have a cost of execution, because when an object cannot be mutated, we need to copy it if we want to write it. When you care about performance (for example, programming a game), you may need to use a mutable object. Even then, it is often better to try to limit the variability of objects.

  • disadvantages

Since an immutable object cannot be reused, they are simply used and thrown. A string is a prime example that can create a lot of garbage and can potentially slow down an application due to a large garbage collection.

+2
Jan 03 '17 at 8:41
source share

An immutable class is those whose objects cannot be changed after creation.

Optional classes are useful for

  • Caching purpose
  • Parallel Environment (ThreadSafe)

  • Hard for inheritance

  • Value cannot be changed in any environment.

Example

Row class

Code example

 public final class Student { private final String name; private final String rollNumber; public Student(String name, String rollNumber) { this.name = name; this.rollNumber = rollNumber; } public String getName() { return this.name; } public String getRollNumber() { return this.rollNumber; } } 
0
Mar 14 '17 at 18:24
source share

Another way to create an immutable object is the Immutables.org library :

Assuming the necessary dependencies have been added, create an abstract class with abstract access methods. You can do the same annotation using interfaces or even annotations (@interface):

 package info.sample; import java.util.List; import java.util.Set; import org.immutables.value.Value; @Value.Immutable public abstract class FoobarValue { public abstract int foo(); public abstract String bar(); public abstract List<Integer> buz(); public abstract Set<Long> crux(); } 

Now you can generate and then use the generated immutable implementation:

 package info.sample; import java.util.List; public class FoobarValueMain { public static void main(String... args) { FoobarValue value = ImmutableFoobarValue.builder() .foo(2) .bar("Bar") .addBuz(1, 3, 4) .build(); // FoobarValue{foo=2, bar=Bar, buz=[1, 3, 4], crux={}} int foo = value.foo(); // 2 List<Integer> buz = value.buz(); // ImmutableList.of(1, 3, 4) } } 
0
Jun 23 '17 at 13:39 on
source share

Q: What is an immutable class?

An object is immutable if its state cannot change after construction, immutable objects cannot in any way change other objects to change their state, the fields of objects are initialized only once inside the constructor and will never change again.

Q: How to create an immutable class?

To create an immutable class, you must follow these steps:

  • Make your class final so that other classes cannot extend it.
  • Make all your fields final so that they are initialized only once inside the constructor and never change afterwards.
  • Do not use setter methods.
  • When exposing methods that change the state of a class, you should always return a new instance of the class.
  • If the class contains a mutable object:

Inside the constructor, be sure to use a copy of the clone of the passed argument and never set your mutable field to a real instance through the constructor, this means clients who pass the object after its modification.

Be sure to always return a copy of the field clone and never return an instance of the real object.

Q: The benefits of an immutable class?

thread safe

Link: How to create an immutable class in java

0
Sep 29 '17 at 10:08 on
source share

As a non-native English speaker, I do not like the usual interpretation of “immutable class”, because “constructed class objects are immutable”; rather, I myself am inclined to interpret this as "the class object itself is immutable."

However, the "immutable class" is a kind of immutable object. The difference is to answer the question of what is the use. In my knowledge / interpretation, an immutable class does not allow its objects to change runtime behavior.

0
Oct 15 '17 at 3:17
source share



All Articles