One thought on “Canonicalization in Java

  1. Vineet says:

    Hi,

    Canonicalization in Java means replacing multiple objects with single object. It reduces the number of object creation and allows the comparison by identity. This is used for ready only objects. This helps to provide the memory and speed.Here idea is used to use garbage collection less frequently. Lesser number of garbage collection happens, lesser overhead occurs.

    e.g. Boolean object which can hold true and false can be canonicalized by making contructor private.This allows the identity comparison than equality.

    e.g. String can be canonicalized by using String.intern().

    This can be achieved either by wrapping object with another one or by using user defined subclass.
    Also achieved by replacing constant objects by integers. Alternatively we can use the Java Enum type.

    Example,

    Suppose we need to create a lot of Integer objects containing values from 1 to 10, so instead of creating seperate Integer objects and calling integerValue() its better to create Integer objects as follows:

    public class IntManager{
    public static final Integer ZERO=new Integer(0);
    public static final Integer ONE=new Integer(1);
    ………………
    }

    Compare as below,

    if (i==IntManager.ZERO)
    {
    …………….
    }
    else if( i==IntManager.ONE)
    {
    …………..
    }
    else ……

Leave a Reply

Your email address will not be published. Required fields are marked *