Shankh is London based consultancy started on 2011 to provide consultancy services primarily in Java. With several successful Java projects under our belt, we started exploring mobile based services towards end of 2012 which led to our first android/ios/windows-phone app which is staged for release in 2013

Some Random quotes


Innovation distinguishes between a leader and a follower. -Steve Jobs

It is not that i am smarter than others, i just persist with problems longer

Archive: programming

Remove duplicates from a list in Java

There is a simple way to remove duplicates from Lists, use HashSet or LinkedHashSet. HashSet will not preserve the ordering while LinkedHashSet will preserve it. Here is the sample code

List<String> listWithDuplicates = 
   Arrays.asList("to","be","or","not","to","be","that","is","the","question");
List<String> listWithoutDuplicates = 
   new ArrayList<String>(new LinkedHashSet<String>(listWithDuplicates));
List<String> listWithoutDuplicatesWithoutOrdering = 
   new ArrayList<String>(new HashSet<String>(listWithDuplicates));

Here is the output

List with duplicates:[to, be, or, not, to, be, that, is, the, question]
List with out duplicates:[to, be, or, not, that, is, the, question]
List with out duplicates without ordering:[not, to, that, is, or, question, the, be]

Share

Hashtable Collisions and String Hashcode

Hash based collections is an interesting aspect of Java language although many developers shy away from using them due to the complexities involved. Some of the complexities are in very subtle form that even experienced programmers tend to make mistakes while using them. In this post I will be talking about Hashtables and collisions while using hash table.

So what is a Hashtable ? Wikipedia defines hashtable like this:
“In computer science, a hash table or hash map is a data structure that uses a hash function to efficiently map certain identifiers or keys (e.g., person names) to associated values (e.g., their telephone numbers). The hash function is used to transform the key into the index (the hash) of an array element (the slot or bucket) where the corresponding value is to be sought. ”

Now Consider this code snippet

import java.util.HashMap;
import java.util.Map;

public class HashFunction {

	private int hashCode;

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
	       Map hashTable = new HashMap();

	       HashFunction key1 = new HashFunction();
	       HashFunction key2 = new HashFunction();

	       hashTable.put(key1, 1);
	       hashTable.put(key2, 2);

	       System.out.println("Size = " + hashTable.size());
	       System.out.println("Value when key1 is searched:"+hashTable.get(key1));
	       System.out.println("Value when key2 is searched:"+hashTable.get(key2));

	}

	public int hashCode() {
		hashCode=10;
		return hashCode;
	}

	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null || getClass() != obj.getClass())
			return false;
		HashFunction other = (HashFunction) obj;
		if (hashCode != other.hashCode)
			return false;
		return true;
	}
}

What will be the output of this program? See the output given below.


Size = 1
Value when key1 is searched:2
Value when key2 is searched:2

Is that result surprising? If it is not surprising to you then there is no need to read further as you are already a master of hashtable :-) . For the rest, here is the explanation for this behaviour.
Size=1 means there is only one value inside the hashtable. And when we searched for a key it returned only key2 value. So we can infer that key2 is the only value inside the hash table. But hang on. How come it returned key2 value when we were searching for key1. Why did this happen? For understanding that we need to look into how hashtable works.
Hashtable consists of key/value pairs which are internally stored in buckets/bins. The values are stored in appropriate buckets based on the hashValue computed for the key.

HashTable Buckets

So far the concept is good, but why did our program behave differently
Now what happened in our code? When we put key2, the hashcodes of the key are same and so collision happens. When we put a value into a hastable, it calculates the hashcode of the key first and if there is already a value present then it calls the equals method and only if they are not equal, it will insert new value into the hashtable. If the Equals method is also returning true then the ‘put’ operation will replace the existing value and return the old value. See the documentation of put to know more about this operation
Hashtable put operation

Now you understand why people like Joshua Bloch and Brian Goetz reiterates the importance of implementing hashcode and equals properly. Please note that the hashcode calculation and equals method in the above program is just to show you this collision and you should use the proper way of implementation as mentioned here. HashCode and Equals
Now how can I correct this program? Replace the hashcode=10; line with the following code

hashcode= System.identityHashCode(this);

Now the output is the following

Size = 2
Value when key1 is searched:1
Value when key2 is searched:2

[update: System.identityHashcode is not guaranteed to produce unique hashcodes and in a 64 bit system there is high chance of collisions. One has to implement a proper equals method to maintain hashtable data integrity. My example is just to explain hashtable collisions and you should always use the proper way of equals implementation as mentioned earlier]

Now time for a bit of fun with string hashcode calculation. What is the output for following code snippet?

String string1 = new String("BB");
String string2 = new String("Aa");
System.out.println("BB hash Code:"+string1.hashCode()+
		   ",Aa hash Code:"+string2.hashCode());


BB hash Code:2112,Aa hash Code:2112

So both of them are having same hashcode. Still there won’t be any collision when you insert them as the key. So let us add a bit more twist. What about the following code?

Hashtable hashtable = new Hashtable();
hashtable.put(string1.hashCode(), 1);
hashtable.put(string2.hashCode(), 2);

We created another collision. Please note that we don’t normally put hashcode as the key and instead will put the object. Hashtable implementation will always calculate the hashcode of the key. In this case the key is an integer and so System will calculate hashcode of that integer. I did it in that way just to show that hashcodes of those two strings are same and hence the key as well as key’s hashcodes will be same.

Share

Equals Method in StringBuffer

Consider this code snippet

StringBuffer s1 = new StringBuffer("shankh");
StringBuffer s2 = new StringBuffer("shankh");
		
System.out.println("Equality Check 1:"+(s1==s2)); //returns false as expected
System.out.println("Equality Check 2:"+(s1.equals(s2))); 
//returns false but was expecting true

Why did the equals method return false? The answer lies in one of the most common mistakes of Java equals usage. StringBuffer doesn’t override the equals method and it is using the equals method inherited from Object. So behind the scenes you ended up checking this if(s1==s2) and not comparing the contents.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/StringBuffer.html

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html#equals%28java.lang.Object%29states
“The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).”

If you want to compare the contents of StringBuffer then this is one way of doing it.

System.out.println("Equality Check 3:"+(s1.toString().equals(s2.toString())));
 //true as expected

It works fine as String overrides the equal method defined in Object Class.

There is an interesting article written by the Scala guys(Martin Odersky, Lex Spoon, and Bill Venners) about implementing equality in Java. http://www.artima.com/lejava/articles/equality.html

Reblog this post [with Zemanta]
Share

Clear Flash Log file

Few days back one of my colleagues, a flash developer was asking about any simple utility available to clear the flash log created by the debug flash player. Flash Debug player will log the output to this folder in windows
C:\Documents and Settings\\Application Data\Macromedia\Flash Player\Logs\ . After testing the code, it is very annoying to go to that folder, open the file and then clear the log. He wanted a simple one click utility to clear the flashlog file without deleting the file (he is tailing the file using baretail)

So i wrote a simple batch script to do that trick.You can download it here Clear Flash Log Utility

Download the attached zip file to your desktop and unzip it. Inside that there is a file called Clear Flash Log.bat. Open the file in any text editor like notepad or wordpad. On line 3 replace the word ‘your_windows_user_name’ with the username you are using to log into windows. Save it and hooray!!! you have got a simple flash log clearing utility. I am curious to hear whether this was helpful for anyone else …

Share

JavaFx Coding Challenge Results

musicExplorerFx Image

musicExplorerFx Image

1st Place


Music Explorer FX, Sten Anderson

lifescope image

lifescope image

2nd Place

Lifescope, Naoaki Suganuma

shining EtherFx Image

shining EtherFx Image

3rd Place

ShiningEtherFX, Evgeni Sergeev

No Image Student Prize

Caesar Photobook Mobile, Ramin Mohammadi

Real Track car race Image

Real Track car race Image

Student Prize

Real Track Car Race, Diego Benna

Calcfx image

Calcfx image

Student Prize

CalcFX, Kazuki Hamasaki

Congratulations to all winners. Well Done !!! Of all the entries MusixExplorerFx looks really cool and no wonder it got the first prize.

Share


RECENTPOSTS

MOSTCOMMENTS

MYARCHIVE