Thursday, January 6, 2011

Making Collections read only

Making a Collection Read-Only

Making a collection read-only involves wrapping the collection in another object whose mutation methods all throw UnsupportedOperationException.

List stuff = Arrays.asList(new String[]{"m", "d"});

// Make a list read-only

List list = new ArrayList(stuff);

list = Collections.unmodifiableList(list);

try {

// Try modifying the list

list.set(0, "value");

} catch (UnsupportedOperationException e) {

// Can't modify

}

// Make a set read-only

Set set = new HashSet(stuff);

set = Collections.unmodifiableSet(set);

// Make a map read-only

Map map = new HashMap();

// Add key/value pairs ...

map = Collections.unmodifiableMap(map);

Shuffling the Elements of a List or Array

Shuffling the Elements of a List or Array

Use Collections.shuffle() to randomly reorder the elements in a list.

// Create a list

List list = new ArrayList();

// Add elements to list

// Shuffle the elements in the list

Collections.shuffle(list);

// Create an array

String[] array = new String[]{"M", "e", "g", "h", "a"};

// Shuffle the elements in the array

Collections.shuffle(Arrays.asList(array));

Comparing three implementations of List interface

Comparing three implementations of List interface 

Classes implementing List

Underlying data structure

Pros

Cons

ArrayList

array

1.        Faster to access by index

 

2.        Faster than Vector as methods are not synchronized

1.        Insertion or deletion in the middle is slower.

2.        Not thread –safe.

3.        Searching is sequential and hence not very efficient.

Vector

array

1.        Faster to access by index.

 

2.        Thread-safe access

1.        Insertion or deletion in the middle is slower.

2.        Slower than ArrayList as methods are synchronized.

3.        Searching is sequential and hence not very efficient.

LinkedList

doubly linked list

1.        Allows faster inserts/delete at any location*

2.        Faster than Vector as methods are not synchronized.

1.        Accessing element by index is slower.

2.        Searching is sequential and hence not very efficient.

Comparing three implementations of Set interface

Comparing three implementations of Set interface 

Classes implementing Set

Underlying data structure

Pros

Cons

HashSet

hash-table

1.        Useful when you want to impose only uniqueness among elements.

2.        Faster than other Set implementation as it does not need to maintain any order.

1.        Do not guarantee any order among elements.

2.        Not thread –safe.*

LinkedHashSet

hash-table

and

doubly linked list

1.        Maintains the insertion order.

1.        Slower than HashSet as it maintains the insertion order.

2.        Not thread –safe.*

TreeSet

tree

1.        Maintains the natural order among elements.

2.        You can impose different order by passing your own Comparator.

1.        Not thread –safe.*

Wednesday, December 8, 2010

Determine if Class or Interface??

How to determine if a Class object represents a Class or Interface??

You can determine by calling isInterface method in Class-
...
Class cls = java.lang.String.class; 
// returns true as String is a class and not an Interface
boolean isClass = !cls.isInterface();
cls = java.lang.Cloneable.class; 
isClass = !cls.isInterface(); // false as Cloneable is an interface, note negation sign
...

So at runtime if you want to know about the entity you are working with, the Class or Interface, you can use the above method.

Tuesday, December 7, 2010

Break Oop's concepts - Java Reflection API

As you all know that we can not access private members of a class, but using Java Reflection API you can. Yes you can break Oops concept by accessing private variable, by calling private methods and also you can create an instance of class which is having private constructor-

Access private members of a class

/**
Class having only one private member
*/

package com.examples;
class test
{
private int youCanAccessMe;
}


Now to access "youCanAccessMe" variable -

package com.examples;
import java.lang.reflect.Field;
public class ReflectExample
{
public static void main(String args[])
{
try
{
Class cls = Class.forName("com.examples.test");
Object obj = cls.newInstance();
Field[] fields = cls.getDeclaredFields();
for( int i = 0 ; i <>fields[i].setAccessible(true);
System.out.println("Field Name-->"+fields[i].getName()+"\t"
+"Field Type-->"+ fields[i].getType().getName()+"\t"
+"Field Value-->"+ fields[i].get(obj));

}
}
catch(Exception e)
{
System.out.println("Exception occured" + e);
}
}
}

You can get the Class object and using Class object you can also create an object of class.
Class cls = Class.forName("com.examples.test");
Object obj = cls.newInstance();
To access private member variable, you have to call setAccessible method to set accessibility level to true.
fields[i].getName() - To get name of variable
fields[i].getType().getName() - To get the type of variable
fields[i].get(obj) - To get its values
Thus Reflection is a powerful approach to analyze the class at runtime.

New post - which is irrelevant in this blog

Hi, i am publishing this post here, which i liked and is not supposed to post in this blog, but i can't resist posting it. One of my friend(Uday Shankar) has written a very touchy poem(Only people who are in love or had break up can understand).

"beautiful memories".

We had our first glance,
that was the start of our romance.
Then we had a small talk
while we had a pleasant walk.

We had some fortunate encounters
and we became regular chatters.
We always enjoyed each others company
so we started meeting few times ... then many.

Love was in the air,
each other was all, we care.
One day those feelings were expressed.
From that moment life get blessed.

We had our first fight,
but we can't live without others sight.
so we make up our mind,
to never leave each other behind.

Don't know what had gone wrong
I'm feeling dreadful for so long
The life has parted our ways
But those were my most beautiful days.