Sunday, November 16, 2014

Internal Working of HashMap<String, Integer> in Java

Internal Working of HashMap in Java

Was reading an blog on how hashMaps work in Java and I was actually surprised to know that it uses the concepts like bucket, chaining and collision in them. I had learned about these concepts in college but thought those books were outdated and now they use some complex techniques for Hashes in Java. So I started a investigation to verify if they were actually using these techniques which i learned in college. Read some articles in wiki, other blogs and went through some youtube videos to actually understand how a HashMap (with key as string) works. Wrote the following code, and debugged it line by line to understand the internals of HashMap.

I will try to explain how a hashMap(key-String) works with debugging the put() and get().
By default the HashMap in Java, is an array(size:16(buckets) and indexed:0,1..15) of Entry<K,V> (K:Key, V:Value).This array is named as table.
Entry is class with key(of type K), value (of type V), hash (int) and 'next' pointing to next Entry in the list. table[i] contains the first Entry of the linkedList for bucket with index i. If the linkedList contains more entries, those can be traced by looping through the `next` of the Entry.

Adding Entry into HashMap : put()
Lets take the example of adding (Key="ef",Value=1) to the HashMap
Steps:
1) The HashCode of the new key("ef") is constructed
  To calcluate the hash for a string java uses the following formula
h(s)=\sum_{i=0}^{n-1}s[i] \cdot 31^{n-1-i}
   For our example the hash for "ef" is 3233
  This hash is modified by the HashMap.class to ensure that hashCodes that differ only by constant      multiples at each bit position have a boundednumber of collisions (approximately 8 at default load      factor).
h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4);

2) The bucket index for the hash is calculated, i = h & (length-1);
3) The bucket[i](array of Entry) is checked to see if there exists an entry with the same hash and same key.
If such an entry exists, then value of the found entry is returned
else the new entry is inserted as the head of the linkedList for bucket[i]
( Note : before inserting the new entry, resizing of map is done if number of keys in this map reaches its threshold )

Retrieving a key's value: get()
Steps
1)  Calculate Hash for String/Key
2)  Find Bucket index,i
3) Loop through bucket[i] to find a Entry with hash = Key.hash and same key
if found: return Entry
else: return null

Diagram shows the structure of HashMap
Note : two entries are mapped into table[2], "ef" and "fG" because they have the same hash. The newly added entry becomes the head of the linkedList

Wednesday, November 12, 2014

Executing native shell commands from Java Program - Java.lang.Runtime.exec() Method

Executing native shell commands from Java Program - Java.lang.Runtime.exec() Method

Java.lang.Runtime.exec can be used to execute native shell commands from Java Program. Running native shell commands from Java is not recommended because by doing so you will lose platform independence which is one reason why we use JAVA.

Suppose you want to find files/directories in "C:\Users\josemel\", this can be done from terminal in two ways
1. Navigate to required directory and run "dir" OR
2. Run "dir " from anywhere

The above can be done from Java using exec() function as shown below.


JAVA DOC

Java.lang.Runtime.exec(String[] cmdarray, String[] envp) Method - Executes the specified command and arguments in a separate process with the specified environment.

Parameters:

  • cmdarray - array containing the command to call and its arguments.
  • envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.

Returns:
A new Process object for managing the subprocess

Throws:

  • SecurityException - If a security manager exists and its checkExec method doesn't allow creation of the subprocess
  • IOException - If an I/O error occurs
  • NullPointerException - If cmdarray is null, or one of the elements of cmdarray is null, or one of the elements of envp is null
  • IndexOutOfBoundsException - If cmdarray is an empty array (has length 0)

Friday, June 13, 2014

Hexgon Layout / HoneyComb Layout

Hexagon Layout - Honey Comb Layout


Project: The Path Game 

Objective: To create Hexagon Layout (Honey Comb Layout) for x7 Mode of the game

Solution:


Create a Relative Layout which is placed at the vertical and horizontal center of its parent layout.

Create a Linear Layout (LL5) containing 9 ImageViews (for each hexagon tile in the row) inside the Relative Layout. Align it vertically (android:layout_centerVertical="true") and horizontally (android:layout_centerHorizontal="true") to the center of Relative Layout. Since it has odd number of tiles the middle of the Relative Layout passes through the center tile of LL5.

Create a Linear Layout LL4 containing 8 ImageViews inside the Relative Layout with horizontal alignment to the center of RelativeLayout (Note: no center vertical alignment here). The LL4 has to be placed on top of the LL5 (android:layout_above="@+id/LL5"). Here the middle of the Relative Layout passed between the 4th and 5th tile of the row.

Construct LL3, LL2 and LL1 in similar fashion one on top of the other.
Similarly construct LL6 below LL5, LL7 below LL6, LL8 below LL7 and LL9 below LL8 for lower rows.

Tuesday, June 3, 2014

Custom Swipe Action

Project : The Path Game

Requirement:  Implement swipe (up,down,left & right) action on the a specific layout.
When users swipes on the layout(in red) the header tile moves in the direction of swipe.

Solution:
Create a View.OnTouchListener set it as the on touch listener for the required layout.

Sunday, June 1, 2014

FLIP Animation

Project  : The Path Game

Requirement 
Create flip effect on ImageButtons : When play button is touched, the menu buttons (achievement, leader-board, sound and in-app purchase buttons) should flip-out to become blank tiles and the game-mode(x5, x7 and hex) buttons should flip-in from blank tiles. Play button changes into 'back' button and when 'back' button is touched, game-mode buttons should flip-out and menu buttons should flip in.



Solution
Create two ObjectAnimator for each ImageButton to be flipped, one which animates the rotation around Y axis from 0 to 90 and another from 90 to 180 around Y axis.



Create two functions which uses these ObjectAnimators to create the flipping effect
Now when the play button is clicked, the flipOutLeaderboard() is called which flips out the icon side of the tile and flips in the blank side. When the back button is clicked, flipInLeaderboard() is called which flips out the blank side and flips in the icon side . Here the play button and the back button are one and the same, so a Boolean value has to toggled to record the state of the tile ie user facing side of the tile.