Showing posts with label immutable. Show all posts
Showing posts with label immutable. Show all posts

Friday, 29 August 2014

What is the difference between STRINGBUFFER and STRING?

What is the difference between STRINGBUFFER and STRING?
String object is immutable. i.e , the value stored in the String object cannot be changed. For e.g.
String myString = “Hello”;
myString = myString + ” Guest”;
System.out.println("myString " + myString);
When you run System.out on myString  the output will be “Hello Guest”. Although we made use of the same object (myString), internally a new object was created in the process because -  String is an immutable class in java . That’s a performance issue.
StringBuffer/StringBuilder objects are  mutable   StringBuffer/StringBuilder objects are mutable i.e. we can make changes to the value stored in the object. This means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
String str = “Be Happy With Your Salary.''
str += “Because Increments are a myth";
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
The Output of the code snippet would be: Be Happy With Your Salary. Because Increments are a myth. But here the difference is that only one  object of stringbuffer is created in the example. That improves space complexity of the program. 

Monday, 28 July 2014

Why hashmap key must be immutable?

HashMap is a data-structure where data is organized as key and values pairs. i.e. for every value there must be a  key to be produced to be stored into the hashmap.

Keys are normally generated using hashcode() method.

Key’s hash code is used primarily in conjunction to its equals() method, for putting a key in map and then searching it back from map. So if hash code of key object changes after we have put a key-value pair in map, then its almost impossible to fetch the value object back from map. It is a case of memory leak. To avoid this, map keys should be immutable.

I have already posted how to make objects immutable in one of my previous posts. 

Monday, 21 July 2014

Immutable objects - Java

Immutable Class - 

An immutable class is one whose state can not be changed once created


Rules/Guidelines to make a class immutable in java 


  •  Donot provide / remove all the setter methods of the member variables in the class
  •  Make the class as final . If we donot make it final child class can have setter implementation. 
  •  Make all the fields final and private 

import java.util.Date;

public final class ImmutableClass
{
 private final Integer test1;

 private ImmutableClass(Integer test1)
 {      this.test1 = test1;
 }
     public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
 {
  return new ImmutableClass(fld1, fld2, date);
 }

 //Provide no setter methods

 public Integer getTest1() {
  return test1;
 }