Skip to main content

Posts

Showing posts from March, 2009

Autoboxing example

You can’t put a primitive value into a collection since collections can only hold object references. To do so, you need to box primitive values into the appropriate wrapper class. When retriving, you get an object out of the collection and you need to unbox the it. Java 5 provides autoboxing and unboxing feature that eliminates the pain. import java.util.ArrayList; public class Autoboxing { public static void main ( String [] args ) { ArrayList list = new ArrayList () ; for ( int i = 0 ; i < 10 ; i++ ){ list.add ( i ) ; } int sum = 0 ; for ( Integer j : list ){ sum += j; } System.out.printf ( "The sum is %d." , sum ) ; } }

Anonymous Classes

Anonymous class is normally used to provide a simple implementation of an adapter class. Many developers don’t just wanna use these because they feel its not really required and is toocomplex. For sure you may do the required task without using anonymous classes but sometimes it is really wise to use these. Let me list features of anonymous classes for you: is a local class without a name is defined and instantiated in a single expression using the new operator anonymous class definition is an expression it can be included as part of a larger expression (method call) When to use it When a local class is used only once, consider using anonymous class syntax. It places the definition and use of the class in exactly the same place. Syntax We use new keyword for defining an anonymous class and creating an instance of that class. It is followed by the name of a class and a class body definition in curly braces. If you wish to subclass your anonymous class, then the name following the new k