Saturday, December 03, 2011

To be upset over what you don't have is to waste what you do have.

To be upset over what you don't have is to waste what you do have.

- Ken Keyes Jr.

The minute you settle for less than you deserve

The minute you settle for less than you deserve, you get even less than you settled for.
- Maureen dowd

Wednesday, November 30, 2011

Better to take many small steps

“It is better to take many small steps in the right direction than to make a great leap forward only to stumble backward.”

Louis Sachar through Julie911

Saturday, October 08, 2011

3 ways to initialize and destroy Spring beans

There are 3 ways to initialize (and destroy) spring beans
1. Using init-method and destroy-method attributes
2. Implementing InitializingBean and DisposableBean interfaces
3. Using @PostConstruct and @PreDestroy Annotations (available only in Spring >=2.5)


1. Using init-method and destroy-method attributes
Certain bean methods can designated as initializing and destroying methods using the init-method and destroy-method attributes. Like so:



<bean
    id="studentService"
    class="initMethod.StudentServiceImpl"
    init-method="subscribe"
    destroy-method="unsubscribe"/>



2. Implementing InitializingBean and DisposableBean interfaces
The bean can implement these methods InitializingBean.afterPropertiesSet() and DisposableBean.destroy(). Like so:

public class StudentServiceImpl implements StudentService, InitializingBean, DisposableBean {
    @Override
    public boolean isExists(long studentId) {
        // A fake implementation
        if ( studentId % 2 == 0 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception 
    {
        // subscribe logic goes here
    }

    @Override
    public void destroy() throws Exception 
    {
       // unsubscribe logic goes here
    }
}



3. Using @PostConstruct and @PreDestroy Annotations
Note that both of these are JSR-250 annotations (here is a nice introduction to JSR-250 support introduced in spring 2.5).

@PostConstruct
public void subscribe()
{
  // subscribe logic goes here
}


@PreDestroy
public void unsubscribe()
{
  // unsubscribe logic goes here
}

Wednesday, September 28, 2011

If the work is worthwhile, then whether we can complete it or not, it's worth making the attempt

If the work is worthwhile, then whether we can complete it or not, it's worth making the attempt. That's why courage is important.
- Dalai Lama

Actions driven solely by anger are of no use at all

Actions driven solely by anger are of no use at all; realizing this can help strengthen your determination to resist it. - DalaiLama

Wednesday, September 21, 2011

Monday, September 19, 2011

One hand

"We are afraid of losing what we have, whether it's our life or our possessions and property. But this fear evaporates when we understand that our life stories and the history of the world were written by the same hand." Sometimes, the caravan (in the middle of a desert) met with another. One always had something that the other needed - as if everything were indeed written by one hand. - The Alchemist by Paulo Coelho

No matter how many detours and adjustments it made, the caravan moved towards the oasis.

"The desert was all sand in some stretches, and rocky in others. When the caravan was blocked by a boulder, it had to go around it; if there was a large rocky area, they had to make a major detour. If the sand was too fine for the animal's hooves, they sought a way where the sand was more substantial... If a guide were to fall ill or die, the camel driver would draw lots and appoint a new one. But all this happened for one basic reason: no matter how many detours and adjustments it made, the caravan moved towards the same compass point. Once obstacles were overcome, it returned to its course, sighting on a star that indicated the location of the oasis." - The Alchemist by Paulo Coelho

Tuesday, September 13, 2011

Don’t ask yourself what the world needs, ask yourself what makes you come alive

“Don’t ask yourself what the world needs, ask yourself what makes you come alive. And then go and do that. Because what the world needs is people who are alive.” - Howard Thurman through Think Simple Now

Friday, September 02, 2011

Saturday, August 20, 2011

I am a parent and do not have the luxury of principles.

Father (who doesn't like his state going to war): I am a parent and do not have the luxury of principles.
...
Son (who is enlisting in the army): Father, I thought you were a man of principles.

Father: When you have a family of your own perhaps you will understand.

Son: When I have a family of my own I won't hide behind them.

- "The Patriot"

Wednesday, August 10, 2011

when each day is the same as the next

"...when each day is the same as the next, it's because people fail to
recognize the good things that happen in their lives every day that the
sun rises."

"The Alchemist" by Paulo Coelho

Thursday, August 04, 2011

Money for good books

"No matter how tight our budget was over the years, we always made money available for good books." - Tim seldin in "How to raise an amazing child The montessori way"
Published with Blogger-droid v1.6.8

Monday, July 18, 2011

There isn’t a way things should be. There’s just what happens, and what we do.

“There isn’t a way things should be. There’s just what happens, and what we do.”

- “A Hat Full of Sky ” by Terry Pratchett through Julie911

I don’t know the key to success, but the key to failure is trying to please everyone.

“I don’t know the key to success, but the key to failure is trying to please everyone.”

- Bill Cosby through Julie911

Friday, July 08, 2011

This is your life. Learn to enjoy what you’ve got.

“This is your life. Learn to enjoy what you’ve got.”

- Mr. Destiny through Julie911

If we cannot love ourselves, we cannot fully open to our ability to love others or our potential to create.

“There are two basic motivating forces: fear and love. When we are afraid, we pull back from life. When we are in love, we open to all that life has to offer with passion, excitement, and acceptance. We need to learn to love ourselves first, in all our glory and our imperfections. If we cannot love ourselves, we cannot fully open to our ability to love others or our potential to create. Evolution and all hopes for a better world rest in the fearlessness and open-hearted vision of people who embrace life.”

- John Lennon through Juliee911

Friday, June 24, 2011

Everybody is a genius

“Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid.”

- Albert Einstein through Julie911

Wednesday, June 08, 2011

When there is no enemy within, the enemies outside cannot hurt you.

When there is no enemy within, the enemies outside cannot hurt you.
- African Proverb through a flourishing life

Monday, May 23, 2011

Reliable and genuine discipline

Reliable and genuine discipline comes not from repression, but from an
understanding of all the whys and wherefores of our actions.

- Dalai Lama

The day we fret about the future is the day we leave our childhood behind.

“When we are children we seldom think of the future. This innocence leaves us free to enjoy ourselves as few adults can. The day we fret about the future is the day we leave our childhood behind.”

- “The Name of the Wind” by Patrick Rothfuss through Julie911

It is what you whisper to yourself that has the most power.

“It is not what you say out of your mouth that determines your life, it is what you whisper to yourself that has the most power.”

- Robert T. Kiyosaki through Julie911

Monday, May 16, 2011

Being deeply loved by someone gives you strength, while loving someone deeply gives you courage.

“Being deeply loved by someone gives you strength, while loving someone deeply gives you courage.”

- Lao Tzu through Julie911

Sunday, May 15, 2011

A trustworthy person

"It is rare in this world to meet a trustworthy person who truly wants to help you, and finding such a person can make you feel warm and safe, even if you are in the middle of a windy valley high up in the mountains."

- Lemony Snicket in "Bitter Truths You Can't Avoid"
Published with Blogger-droid v1.6.8

Crying

"Unless you have been very, very lucky, you have undoubtedly experienced events in your life that have made you cry. So unless you have been very, very lucky, you know that a good, long session of weeping can often make you feel better, even if your circumstances have not changed one bit."

- Lemony Snicket in 'Bitter Thruths You Can't Avoid'

Frustration brings out the worst in oneself

"Frustration is an interesting emotional state, because it tends to bring out the worst in whoever is frustrated."

- Lemony Snicket in 'Bitter Thruths You Can't Avoid'

Shyness

Shyness is a curious thing, because, like quicksand, it can strike people at any time, and also, like quicksand, it usually makes its victims look down.

- Lemony Snicket in 'Bitter Thruths You Can't Avoid'

Courage

"If one's safety is threatened, one often finds courage one didn't know one had."

- Lemony Snicket in 'Bitter Thruths You Can't Avoid'

One's regrets

"One of the most difficult things to think about in life is one's regrets. Something will happen to you, and you will do the wrong thing, and for years afterward you will wish you had done something different."

- Lemony Snicket in 'Bitter Thruths You Can't Avoid'

Times to stay put and times to go out and find

"There are times to stay put, and what you want will come to you, and there are times to go out into the world and find such a thing for yourself."

- Lemony Snicket in 'Bitter Thruths You Can't Avoid'

An island in the middle of a vast sea of ignorance

"A library is like an island in the middle of a vast sea of ignorance, particularly if the library is very tall and the surrounding area has been blooded."

- Lemony Snicket in 'Bitter Thruths You Can't Avoid'

A good library

"A good library will never be too neat, or too dusty, because somebody will always be in it, taking books off the shelves and staying up late reading them"

- Lemony Snicket in 'Bitter Thruths You Can't Avoid'

When people ask you if you play a certain game...

"When people ask you if you play a certain game, it is likely that hey are very good at that sport and are hoping you are only mediocre so that you can waste an afternoon losing a game. In such instances the safest action is to run away very quickly as soon as the question is asked."

- Lemony Snicket in "Bitter Truths You Can't Avoid"

Wednesday, April 20, 2011

Forget what one is leaving behind and focus all attention on the task at hand

When being dropped off on his attempt to reach north pole on foot.

"I was now fully aware that from here on, I would be totally alone in the face of my challenge. Until now, I had been helped, surrounded, financed, supported, and conveyed by people who believed in me. But once that helicopter lifted off and carried away the last of those people, it would be up to me to play this game -- me and me alone."..."Nobody said another word. The emotions were beyond words. Everyone knew that what I was about to try to do would define the next stage of my life."..."Everyone climbed back into the helicopter, which quickly took off. I turned my back on the aircraft as it labored into the air, to face what awaited me. For the moment, what I most needed to do was to forget what I was leaving behind and focus all my attention on the task at hand."

- Mike Horn in 'Conquering the Impossible"

stay alive ... then make it through

"in the virgin jungle of amazon. My original goal had been to make it through the jungle. Then, after being bitten by a poisonous snake and struggling for five days, balanced on the brink of death, my goal changed. It became to stay alive ... then make it through the jungle."

- Mike Horn in "Conquering the impossible"
Published with Blogger-droid v1.6.8

Friday, April 15, 2011

The line between good and evil

The line between good and evil runs "through the human heart,"

- Alexander Solzhenitsyn

Nice prayer

May I be a guard for those who need protection
A guide for those who are in the path
A boat for those to cross the flood
May I be a resting place for the weary
A healing medicine for those who are sick
Food for the hungry
May I be a lamp for those in darkness
May I bring sustenance for awakening
Until all being are free from sorrow and all are awake and together.

- Shanti Dev (Ancient Indian Sage)

Thursday, April 14, 2011

Assets of an explorer

"Objectively, I can say that I posses two main assets as an explorer: a rock solid temperament and a solid capacity for physical endurance."

- Mike Horn in 'Conquering the Impossible'

Preparation and training for success

"I did have enough experience to know one thing. I didn't have a prayer of succeeding without the kind of rigorous preparation and training that would make me capable of surviving in that (north pole) environment."

- Mike horn in 'Conquering the impossible'

Wednesday, March 30, 2011

A Brief for the Defense

Sorrow everywhere. Slaughter everywhere. If babies
are not starving someplace, they are starving
somewhere else. With flies in their nostrils.
But we enjoy our lives because that's what God wants.
Otherwise the mornings before summer dawn would not
be made so fine. The Bengal tiger would not
be fashioned so miraculously well. The poor women
at the fountain are laughing together between
the suffering they have known and the awfulness
in their future, smiling and laughing while somebody
in the village is very sick. There is laughter
every day in the terrible streets of Calcutta,
and the women laugh in the cages of Bombay.
If we deny our happiness, resist our satisfaction,
we lessen the importance of their deprivation
.
We must risk delight. We can do without pleasure,
but not delight. Not enjoyment. We must have
the stubbornness to accept our gladness in the ruthless
furnace of this world. To make injustice the only
measure of our attention is to praise the Devil.
If the locomotive of the Lord runs us down,
we should give thanks that the end had magnitude.
We must admit there will be music despite everything.
We stand at the prow again of a small ship
anchored late at night in the tiny port
looking over to the sleeping island: the waterfront
is three shuttered cafés and one naked light burning.
To hear the faint sound of oars in the silence as a rowboat
comes slowly out and then goes back is truly worth
all the years of sorrow that are to come.

- Jack Gilbert

Master your senses

Master your senses

What you taste and smell
What you see
What you hear

In all things
Be a Master
of what you do
and say
and think
Be Free

Are you quiet?

Calm your body
Calm your mind

By your own efforts

Waken yourself
Watch yourself

And live Joyfully

Follow the truth of The Way

Reflect upon it

Make it your own

Live it

It will always sustain you

- Buddha

Live in Joy

Live in Joy
in Love
Even among those who hate

Live in Joy
in Health
Even among the afflicted

Live in Joy
in Peace
Even among the troubled

Look within
Be still

Free from fear and attachment
Know the sweet joy of the way

- Buddha

Tuesday, March 29, 2011

All that we love deeply becomes a part of us

“What we once enjoyed and deeply loved we can never lose, for all that we love deeply becomes a part of us.”

- Helen Keller through Julie911

Friday, March 11, 2011

Your home team

Everybody has a home team: It’s the people you call when you get a flat tire or when something terrible happens. It’s the people who, near or far, know everything that’s wrong with you and love you anyways.

These are the ones who tell you their secrets, who get themselves a glass of water without asking when they’re at your house.

These are the people who cry when you cry. These are your people, your middle-of-the-night, no-matter-what people.

- “Bittersweet” by Shauna Niequist" through Julie911


Each person deserves a day away in which no problems are confronted, no solutions searched for.

“Each person deserves a day away in which no problems are confronted, no solutions searched for.”

- Maya Angelou through Julie911

Tuesday, March 01, 2011

Class diagram notations and their Java interpretations

Inheritance:


interface list extends Collection;

class ArrayList extends AbstractList;

Realization:


class ArrayList implements List;

Dependency:

When a class has a reference to another class or interface (in instance variables, arguments, local values, return values or anywhere else) then there is a dependency



class DriverManager {
...
Connection getConnection(String url);
...
}


Association:

An association is a special type of dependency. All associations are dependencies. An association is used when the dependency is always there (as opposed to dependency existing only during the course of a method execution). Its more often (not always) used to represent a field in a class. For more information see here.


class Order {
private Customer customer;
}

Monday, February 28, 2011

The best things in life are nearest

“The best things in life are nearest: Breath in your nostrils, light in your eyes, flowers at your feet, duties at your hand, the path of right just before you. Do not grasp at the stars, but do life’s plain, common work as it comes, certain that daily duties and daily bread are the sweetest things in life.”

- Robert Louis Stevenson (1850-1894) through Julie911

Friday, February 25, 2011

Primitive types vs. Boxed Primitives

Java has primitive types like int, short, float, double etc... and reference types like String, Collection etc... Each of the primitive types also has a equivalent reference type. int has Integer, long has Long and so on. These reference types are called Boxed primitives.

Primitive types vs. Boxed Primitives
Primitive Types
Boxed Primitives
Support only functional values (1, 4.5 etc...)
Supports functional values and null
Time and space efficient
Less time and space efficient than primitive types
Have only values. 4 == 4.
Have values and an identity. new Integer(4) != new Integer(4). So avoid using == on boxed primitives

Consider the following code:

public class Test
{
    Integer i; // Initialized to null
    public static void main(String[] args)
    {
        if ( i == 45 ) // 1. auto-unbox i (convert Integer to int) 2. NullPointerException as i value is null.
        {
            System.out.println( "i is 45." );
        }
    }
}

In the above example, i is initialized to null (since its a instance variable). Subsequently, when i == 45 is encountered, i is first auto un-boxed (converted from Integer to int) and this conversion fails because i is null. Fix this by declaring i as int (instead of Integer).

Moral of the story:
Prefer using primitives over boxed types. If using boxed types follow these:
1. Must not be using == operator with boxed types (none of the operands to == must be a boxed type). If used,
a. References are compared, not values and hence results will (in most cases) be wrong.
b. If one operand is primitive and other is boxed primitive, then the boxed primitive is un-boxed. This un-boxing could throw a NullPointerException.
2.
If using boxed types with other operator (like +=), consider overhead involved in auto-boxing and un-boxing. Integer i = 10; i += 2; // un-box value of i, add 2 to unboxed value and box the result back into i. Not efficient.

Use Boxed primitives when:
1. Using parameterized types (list Collection).
Parameterized types do not permit primitives.
2. Using value as a key or value in Collections.
3. Using reflective method invocation (another don't do). e.g. class.forName("java.lang.Integer");

Source: Effective Java by Joshua Bloch

Tuesday, February 22, 2011

Harmony avoids them

Straighten yourself and you will not stand steady;
Display yourself and you will not be clearly seen;
Justify yourself and you will not be respected;
Promote yourself and you will not be believed;
Pride yourself and you will not endure.

These behaviours are wasteful, indulgent,
And so they attract disfavour;
Harmony avoids them.

- Tao Te Ching

Saturday, February 19, 2011

Liberation is sustained by

Liberation is sustained by seeing clearly.
Seeing clearly is sustained by joy, serenity & concentration,
These are sustained by confidence,
Confidence is sustained by association with good spiritual friends

- buddha

Thursday, February 17, 2011

You’ve got to get out ahead of change. You can’t be behind the curve.

"if you are governing these countries, you've got to get out ahead of change. You can't be behind the curve." - Obama on protests in Bahrain.

The lesson: If you must have control, "
you've got to get out ahead of change. You can't be behind the curve."

Wednesday, February 16, 2011

This is to have succeeded

To laugh often and much;
To win the respect of intelligent people and the affection of children;
To earn the appreciation of honest critics and endure the betrayal of false friends;
To appreciate beauty, to find the best in others;
To leave the world a bit better, whether by a healthy child, a garden patch or a redeemed social condition;
To know even one life has breathed easier because you have lived.
This is to have succeeded.

- Ralph Waldo Emerson

Tuesday, February 15, 2011

Java 6 Collection Interfaces and Abstract Classes

The following is a class diagram of Java 6 collection interfaces and abstract classes. The diagram does *not* included concrete implementations (coming soon).

Click on image for detailed view.

Failure and Guilt

When failure results from effort and you did everything within your
ability, then you do not (and should not) have guilt. But how do you
find your ability? By trying.

- Jeff Hunt (Paraphrased)

You become strong at whatever you repeat

Whatever it is that you repeat, you become strong. If you take more
decisions influenced by your virtues, you will become a more stronger
person. If you take more decisions influenced by your weakness or evils
you will become a weaker person.

So choose to take decisions influenced by your virtues.

- Jeff Hunt (paraphrased)

Sunday, February 13, 2011

Fetching database rows using ResultSet in JDBC

The basic approach to fetching rows from DB:

Connection con = // Secure a connection using this approach
Statement stat;
try
{
stat = con.createStatement();
ResultSet rs = stat.executeQuery("select * from emp");
while ( rs.next() ) // Move cursor 1 row forward, false returned means last row
{ // next | previous | first | last | beforeFirst | afterLast |
// relative (int) | absolute(int)
String empName = rs.getString("EMP_NAME"); // or getString()
int empId - rs.getInt("EMP_ID");
..
}
} catch( SQLException e)
{
...
} finally
{
stmt.close();
}

ResultSet types:

TYPE_FORWARD_ONLY [DEFAULT]: Only scroll forward (not backward) - insensitive to changes made by others (Contains results as they existed at query execution time or as rows are retrieved - depends on how db generated results)

TYPE_SCROLL_INSENSITIVE: Scrolls back, forward and to absolute or relative position. insensitive to changes made by others (Contains results as they existed at query execution time or as rows are retrieved - depends on how db generated results)

TYPE_SCROLL_SENSITIVE: Scrolls back, forwards and to absolute or relative position. Changes made by others at the data source are reflected in the ResultSet.

ResultSet concurrency:

CONCUR_READ_ONLY [DEFAULT]: No support for updates using ResultSet Interface
CONCUR_UPDATABLE: Supports updates using ResultSet. Not supported by all JDBC drivers. Call DatabaseMetaData.supportsResultSetConcurrency to know support.

E.g.:

Statement stmt =
con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM EMP");
rs.next();
rs.updateString("NAME", "NewName"); // Update EMP set Name="NewName";

Cursor Holdability:
When connection.commit() is invoked, all ResultSets opened as part of the transaction are, by default, closed. If they are not to be closed, then the ResultSet object's holdability needs to be changed.

HOLD_CURSORS_OVER_COMMIT: When connection.commit() is invoked, do not close the ResultSet objects opened during the connection. Useful with read only result sets.
CLOSE_CURSORS_AT_COMMIT: On connection.commit() close ResultSets. Some applications get performance improvements in doing do.

Use JDBCTutorialUtilities.cursorHoldabilitySupport to determine support for holdability.

These are specified in Connection methods.

Friday, February 11, 2011

Links in Linux

Links help replicate a file to multiple location without creating redundant copies. The links point to the source file (as opposed to copying the file-contents). Any changes done to source file (after linking) are reflected in the links. Dangling links can be created to non-existent files.

There are 2 types of links: Hard links and Symbolic links.

Hard Links
Symbolic Links
Each hard link is a reference to the same i-node number (a key in the i-node table - inode entry for a file can be viewed using stat<<filename>>).
Each symbolic link contains the pathname of the source file.
Source cannot be a directory
Source can be a directory
Source & destination must be in the same file systems (because inode numbers are unique only within one file system)
Source and destination can reside anywhere


e.g.:
~/temp$ ls --inode source.txt # List file with inode number
2131296 source.txt

~/temp$ cp --link source.txt link-copied.txt # a hard link

~/temp$ cp --symbolic-link source.txt symbolic-link-copied.txt # a symbolic link

~/temp$ ls --inode source.txt link-copied.txt symbolic-link-copied.txt
2131296 link-copied.txt 
2131296 source.txt # hard link: i-node numbers of source and destination files are same
2133544 symbolic-link-copied.txt # symbolic link: i-node numbers differ

Tuesday, February 08, 2011

Simple Spring bean configuration

Singular property

Simple property

Class Singer implements Performer

{

private String name;

public Singer(String n)

{

this.name = n;

}

}

<bean

id=”xyz”

class=”com.Singer”>

<constructor-arg

value=”xyz”/>

</bean>

Class Singer implements Performer

{

private String name;

public void setName(String n)

{

this.name = n;

}

}

<bean

id=”xyz”

class=”com.Singer”>

<property

name=”name”

value=”xyz”/>

</bean>

Property referencing another bean

Class Drummer implements Performer

{

private Drum drum;

public Drummer(Drum d)

{

this.drum = d;

}

}

<!-- Tabla implements Drum -->

<bean

id=”tabla”

class=”com.Tabla”>

</bean>

<bean

id=”xyz”

class=”com.Drummer”>

<constructor-arg

ref=”tabla”/>

</bean>


OR


<bean

id=”xyz”

class=”com.Drummer”>

<constructor-arg>

<!-- nested bean -->

<bean

class=”com.Tabla”>

</constructor-arg>

</bean>



Class Drummer implements Performer

{

private Drum drum;

public void setDrum(Drum d)

{

this.drum = d;

}

}

<!-- Tabla implements Drum -->

<bean

id=”tabla”

class=”com.Tabla”>

</bean>

<bean

id=”xyz”

class=”com.Drummer”>

<property

name=”drum”

ref=”tabla”/>

</bean>


OR


<bean

id=”xyz”

class=”com.Drummer”>

<property

name=”drum”>


<!-- nested bean -->

<bean

class=”com.Tabla”>

</property>

</bean>

Plural Property

Collections



Class Drummer implements Performer

{



// REFERENCE TYPE

private Collection<Drum> drums;

OR

private List<Drum> drums;

OR

private Set<Drum> drums;

public setDrums(

Collection<Drum> drums)

{

this.drums = drums;

}






// SIMPLE TYPE

private Collection<String> names;

public setNames(Coll... names)

{

this.names = names;

}

}

<bean id=”drum1” … />

<bean id=”drum2” … />

<bean

id=”xyz”

class=”com.Drummer”>


<!-- REFERENCE TYPE -->

<property

name=”drums”>

<list or set>

<ref bean=”drum1” />

<ref bean=”drum2” />

<bean

class=”com.ADrum”/>

<null />

</list or set>

</property>


<!-- SIMPLE TYPE -->

<property

name=”names”>

<list or set>

<value>Name1</value>

<value>Name2</value>

<null />

</list or set>

</property>

</bean>

Name value pairs



Class Drummer implements Performer

{


// Key and values are objects

private Map<String, Drum> drums;

public setDrums(Map... drums)

{

this.drums = drums;

}








// key & values are strings

private Properties notes;

public setNotes(Properties note)

{

this.notes = note;

}

}

<bean id=”drum1” … />

<bean id=”drum2” … />

<bean

id=”xyz”

class=”com.Drummer”>


<property

name=”drums”>

<map>

<entry

key or key-ref=”drum1”

value or value-ref=”drum1”/>

<entry

key=”drum2”

value-ref=”drum2”/>

</map>

</property>

<property

name=”notes”>

<prop

key=”Note1”>

lala

</prop>

<prop

key=”Note21”>

lolo

</prop>

</property>

</bean>

Monday, February 07, 2011

Iterable interface and "for each" loop

Since Java SE 5.0, the new "for each" loop is supported.

To iterate a Collection, one had to go through the long way as follows:

import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

class IterationUsingIterator
{
    public static void main(String[] args)
    {
        Collection<String> names = new ArrayList<String>();
        names.add( "Jack" );
        names.add( "Jill" );

        Iterator<String> nameIterator = names.iterator();
        while( nameIterator.hasNext() )
        {
            System.out.println( nameIterator.next() );
        }
    }
}

The same loop using "for each" syntax:

import java.util.Collection;
import java.util.ArrayList;

class IterationUsingForEach
{
    public static void main(String[] args)
    {
        Collection<String> names = new ArrayList<String>();
        names.add( "Jack" );
        names.add( "Jill" );

        for( String name : names)
        {
            System.out.println( name );
        }
    }
}


Question: When can a collection (Collection, Array etc...) participate in "for each" syntax?
Answer: When the collection implements Iterable (with a single method Iterator<T> interator()). These includes Collection, List, Set, SortedSet, Queue and a few more collection sub-interfaces (refer to the javadocs). Arrays also support "for each" syntax. But they do not have a "Is A" relationship with Iterable.

Categorized list of Collection interface methods

Collection interface methods categorized:

Boolean

add(E o)

Methods to add elements to collection

Boolean

addAll(Collection<? Extends E> c)

Void

Clear()

Methods to remove elements from collection

Boolean

remove(Object o)

Boolean

removeAll(Collection<?> c)

Boolean

retainAll(Collection<?> c)

Boolean

contains(Object o)

Methods to check if specific element(s) exist in collection.

Boolean

containsAll(Collection<?> c)

Boolean

IsEmpty()

Methods to check collection at a higher level

Int

Size()

Iterator<E>

Iterator()

Methods to transform the whole collection to other representations

Object[]

ToArray()

<T> T[]

toArray(T[] a)