Skip to main content

"immutability" Nature of an Object

Immutability.

A Java object is considered to be immutable when its state (properties and contents) cannot change after it is created.

Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable

Immutable objects are simple to use test and construct.
Immutable objects are thread-safe by default.
Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection). This is the reason most of the times we prefer String objects as Key in many Map Collection objects.
Immutable objects do not require an implementation of clone.
Immutable objects allow hashCode to use lazy initialization, and to cache its return value.


To create a object immutable

Need to make the class final and all its member final so that once objects gets crated no one can modify its state.
Or
By making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

Comments

Popular posts from this blog

NO SQL Types and vendors in market

NO SQL

KEY - VALUE Store  - Similar to a  MAP.
   e.g. Dynamo DB or REDIS

DOCUMENT Sore  - Similar to KEY-VALUE, value can be JSON/XML and key will be unqiuely idnetified this document.
   e.g. Coutch DB or mongoDB.

Column Store - Multi timentional table, identifying data with row and column numbers.
  e.g.  Cassandra or Apache HBase

Graph Store - Store relation between nodes (record entities). It has better transaction management
e.g. Neo4J and Orient DB.




Compress a String

package com.sbs.java8.praticse;

public class StringCompression {

public StringCompression() {
// TODO Auto-generated constructor stub
}

public static void main(String[] args) {
System.out.println(compressString("aaaabbbbbccccAAAAccccccccdefg"));
}

public static String compressString(String str) {
//String str = "aaaabbbbbcccc";
char[] charArray = str.toCharArray();
String compressedString = "";
int i = 0;
while (i < charArray.length) { int counter = 1; int j = i + 1; while (j < charArray.length && charArray[i] == charArray[j]) { counter++; j++; i++; } compressedString = compressedString + charArray[i] + counter; i++; } //System.out.println(compressedString); String output =(compressedString.length() > charArray.length)? str: compressedString;
return output;
}
}