Showing posts with label Collection. Show all posts
Showing posts with label Collection. Show all posts

Thursday, 21 February 2013

Looping javascript 'hashmap'

Leave a Comment
for (var i = 0, keys = Object.keys(a_hashmap), ii = keys.length; i < ii; i++) 
 {
  console.log('key : ' + keys[i] + ' val : ' + a_hashmap[keys[i]]);
 }
Read More...

Monday, 7 January 2013

What are the Legacy classes?

Leave a Comment
Early versions of java did not include Collections framework. Instead it defined several classes and one interface to store objects. When collection came these classes re-engineered to support the Collection interfaces. These old classes are known are legacy classes.
Legacy classes-Dictionary,HashTable,Properties, Stack, Vector
Legacy interface- Enumeration.

• Enumeration ---Interface
• Dictonary ------Abstract class
• Hashtable -----Concrete class
• Properties -----Concrete class
• Vector -----Concrete class
• Stack -----Concrete class


Only values- Stack, Vector
Key/value pair – Dictionary, HashTable, Properties


Enumeration interface:
It defines the method by which we can enumerate(obtain one at a time) through the elements. The legacy interface is suppressed by Iterator.
It has two methods:
Boolean hasMoreElements()
nextElement()
Read More...

Iterator VS Enumeration

Leave a Comment

Both Iterator and Enumeration provides way to traverse or navigate through entire collection in java

Between Enumeration and Iterator, Enumeration is older and its there from JDK1.0 while iterator was introduced later. Iterator can be used with Java arraylist,  java hashmap keyset  and with any other collection classes.


Another similarity between Iterator and Enumeration in Java is that  functionality of Enumeration interface is duplicated by the Iterator interface.

Only major difference between Enumeration and iterator is Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as by using Iterator we can manipulate the objects like adding and removing the objects from collection e.g. Arraylist.

Also Iterator is more secure and safe as compared to Enumeration because it  does not allow other thread to modify the collection object while some thread is iterating over it and throws ConcurrentModificationException. This is by far most important fact for me for deciding between Iterator vs Enumeration in Java.

In Summary both Enumeration and Iterator will give successive elements, but Iterator is new and improved version where method names are shorter, and has new method called remove. Here is a short comparison:

Enumeration
hasMoreElement()
nextElement()
N/A


Iterator
hasNext()
next()
remove()

So Enumeration is used when ever we want to make Collection objects as Read-only.


Read More...

Enumeration Interface

Leave a Comment

The Enumeration interface defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator. Although not deprecated, Enumeration is considered obsolete for new code. However, it is used by several methods defined by the legacy classes such as Vector and Properties, is used by several other API classes, and is currently in widespread use in application code.
The methods declared by Enumeration are summarized in the following table:
SNMethods with Description
1boolean hasMoreElements( )
When implemented, it must return true while there are still more elements to extract, and false when all the elements have been enumerated.
2Object nextElement( )
This returns the next object in the enumeration as a generic Object reference.

Example:

Following is the example showing usage of Enumeration.
import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

   public static void main(String args[]) {
      Enumeration days;
      Vector dayNames = new Vector();
      dayNames.add("Sunday");
      dayNames.add("Monday");
      dayNames.add("Tuesday");
      dayNames.add("Wednesday");
      dayNames.add("Thursday");
      dayNames.add("Friday");
      dayNames.add("Saturday");
      days = dayNames.elements();
      while (days.hasMoreElements()){
         System.out.println(days.nextElement()); 
      }
   }
}
This would produce following result:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Read More...

Saturday, 15 December 2012

Marker Interface in Java: what, why, uses ?

Leave a Comment
What are Marker Interfaces in Java?

An empty interface having no methods or fields/constants is called a marker interface or a tag interface. This of course means if the interface is extending other interfaces (directly or indirectly) then the super interfaces must not have any inheritable member (method or field/constant) as otherwise the definition of the marker interface (an entirely empty interface) would not be met. Since members of any interface are by default 'public' so all members will be inheritable and hence we can say for an interface to be a marker interface, all of its direct or indirect super interfaces should also be marker. (Thanks marco for raising the point. I thought it was obvious, but mentioning all this explicitly would probably help our readers.)

There are few Java supplied marker interfaces like CloneableSerializable, etc. One can create their own marker interfaces the same way as they create any other interface in Java.

Purpose of having marker interfaces in Java i.e., why to have marker interfaces?

The main purpose to have marker interfaces is to create special types in those cases where the types themselves have no behavior particular to them. If there is no behavior then why to have an interface? Because the implementor of the class might only need to flag that it belongs to that particular type and everything else is handled/done by some other unit - either internal to Java (as in the case of Java supplied standard marker interfaces) or an app specific external unit.

Let's understand this by two examples - one in which we will discuss the purpose of a standard Java interface (Cloneable) and then another user-created marker interface.

What purpose does the Cloneable interface serve?

When JVM sees a clone() method being invoked on an object, it first verifies if the underlying class has implemented the 'Cloneable' interface or not. If not, then it throws the exception CloneNotSupportedException. Assuming the underlying class has implemented the 'Cloneable' interface, JVM does some internal work (maybe by calling some method) to facilitate the cloning operation. Cloneable is a marker interface and having no behavior declared in it for the implementing class to define because the behavior is to be supported by JVM and not the implementing classes (maybe because it's too tricky, generic, or low-level at the implementing class level). So, effectively marker interfaces kind of send out a signal to the corresponding external/internal entity (JVM in case of Cloneable) for them to arrange for the necessary functionality.

How does JVM support the 'cloning' functionality - probably by using a native method call as cloning mechanism involves some low-level tasks which are probably not possible with using a direct Java method. So, a possible 'Object.clone' implementation would be something like this:-

public Object clone() throws CloneNotSupportedException {

 if (this implements Cloneable)

     return nativeCloneImpl();

 else

     throw new CloneNotSupportedException();

}

Anyone wondered as to why and when do we get 'CloneNotSupportedException' exception at compile-time itself? Well... that's no trick. If you see the signature of the 'Object.clone()' method carefully, you will see a throws clause associated with it. I'm sure how can you get rid of it: (i) by wrapping the clone-invocation code within appropriate try-catch (ii) throwing the CloneNotSupportedException from the calling method.

What purpose does a user-defined marker interface serve? It can well serve the same purpose as by any standard marker interface, but in that case the container (the module controlling the execution of the app) has to take the onus of making sure that whenever a class implements that interface it does the required work to support the underlying behavior - the way JVM does for Cloneable or any other standard marker interface for that matter.


Defining an user-defined marker interface in Java


Let's define a user-defined marker interface. Let's say there is an app suporting a medical store inventory and suppose you need a reporting showing the sale, revenue, profit, etc. of three types of medicines - allopathic, homeopathic, and ayurvedic separately. Now all you need is to define three marker interfaces and make your products (medicines) implement the corresponding ones.



public interface Allopathic{}
public interface Homeopathic{}
public interface Ayurvedic{}

In your reporting modules, you can probably get the segregation using something similar to below:-



for (Medicine medicine : allMedicines) {
if (medicine instanceof Allopathic) {
//... update stats accordingly
}
else if (medicine instanceof Homeopathic) {
//... update stats accordingly
}
else if (medicine instanceof Ayurvedic) {
//... update stats accordingly
}
else {
//... handle stats for general items
}
}

As you can see the medicines themselves don't need to implement any specific behavior based on whether they are allopathic, homeopathic, or ayurvedic. All they need is to have a way of reflecting which category they belong to, which will in turn help the reporting modules to prepare the stats accordingly.


Now this can be done by having a flag as well... yeah, sure it can be. But, don't you think tagging a class makes it more readable than having a flag indicating the same. You kind of make it an implementation-independent stuff for the consumers of your classes. If your class implements an interface, it becomes part of the class signature of the published API. Otherwise, you would probably handle the situation by having a public final field having the flag set up at the time of instantiation - final because you would not like others to change it. I guess going the marker interface way would probably make more sense in many such situations.


Another advantage of going via marker interface way is that at any point of time you can easily cast the objects of the implementing classes. Again it's not that if you go via public final approach, you can't do that. You can very well do, but casting might look a cleaner approach in many situations.


The bottom-line is there will hardly be any enforced need for a designer/developer to go via that way as there can be possible alternatives, but marker interfaces can surely be a preferred choice for some in some cases.


Note: Annotations are considered as another possible (quite popular as well) alternative to marker interfaces
Read More...

Tuesday, 4 December 2012

Vector Capacity

Leave a Comment

The Vector API defines 4 different constructors:
Vector()

Vector(Collection<? extends E> c)

Vector(int initialCapacity)

Vector(int initialCapacity, int capacityIncrement)
but how do they work and what are they used for? Why should i want to define a fixed capacity for a vector? Even if i set the initial capacity to 100, I can add a 101. item to the vector:
Vector<Object> test = new Vector<Object>(100);
for (int i = 0; i < 100; i++) {
    test.add(new Object());
}

test.add(new Object());
System.out.println(test.size());
System.out.println(test.capacity());
In the above code, the second sysout (test.capacity()) writes 200. Why is the capacity in this vector 200? The initial capacity is 100 and i didn't defined a capacity increment.

What's an "initial" capacity?

The initial capacity is simply that: the capacity of the Vector at construction time.
Vector is a dynamically growable data structure, and it would reallocate its backing array as necessary. Thus, there is no final capacity, but you can set what its initial value is.

Answer:
Each vector tries to optimize storage management by maintaining a capacity and acapacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.

Why doubling?

Without going into details, this doubling in growth is a form of geometric expansion, which is what enabled constant-time amortized analysis per operation for Vector. It's worth noting that ArrayList, a similar growable data structure backed by an array, doesn't even specify the details of its growth policy, but the OpenJDK version has a growth factor of 3/2.
Do note that Vector actually allows you to set a non-geometric growth factor withcapacityIncrementIt's important to realize that if you set capacityIncrement to a small non-zero value, you can in fact make Vector perform horrible asymptotically. If you set it to 1, for example, then adding N elements would be an O(N^2) operation!
ArrayList doesn't let you customize its growth policy, since you're not even supposed to know (nor care, really!).

See also


Read More...

How to copy Key Value Elements from one Hash Table to the other HT

Leave a Comment

Try something like this.
Hashtable h = new Hashtable();
Hashtable h1 = new Hashtable();
Hashtable h2 = new Hashtable();
Set s = h.keySet();
int i = 0;
for (Object key : s) {
    if ( i++ < 3) {
        h1.put(key, h.get(key));
    } else {
        h2.put(key, h.get(key));
    }
}
Add generics etc. as appropriate.

Example:

String key = "hello";
Multimap<String, Integer> myMap = HashMultimap.create();
myMap.put(key, 1);
myMap.put(key, 5000);
System.out.println(myMap.get(key)); // prints either "[1, 5000]" or "[5000, 1]"
myMap = ArrayListMultimap.create();
myMap.put(key, 1);
myMap.put(key, 5000);
System.out.println(myMap.get(key)); // always prints "[1, 5000]"
Note that Multimap is not an exact equivalent of the home-baked solution; Hashtable synchronizes all its methods, while Multimap makes no such guarantee. This means that using a Multimap may cause you problems if you are using it on multiple threads. If your map is used only on one thread, it will make no difference (and you should have been using HashMap instead of Hashtable anyway).


Read More...