Sunday, 19 October 2014

What is HashMap in Java

What is Hashmap?
HashMap in Java is one of the most popular class Collection Framework . The HashMap class uses a hashtable to implement the Map interface.

In above I used "Hash Table" terminology, let's take overview  of "What is Hash Table"
Here's an explanation in laymans terms.
Let's assume you want to fill up a library of books, and not just stuff them in there, but you want to be able to easily find them again when you need them.So, you decide that if the person that wants to read a book knows the title of the book, and the exact title to boot, then that's all it should take. With the title, the person, with the aid of the librarian, should be able to go find the book easily and quickly.
So, how can you do that? Well, obviously you can keep some kind of list of where you put each book, but then you have the same problem as searching the library, you need to search the list. Granted, the list would be smallers, and easier to search, but still, you don't want to search sequentially from one end of the library (or list) to the other.
You want something that, with the title of the book, can give you the right spot at once, so all you have to do is just stroll over to the right shelf, and pick up the book.But how can that be done? Well, with a bit of forethought when you fill up the library, and actually, a lot of work when you fill up the library.
Instead of just starting to fill up the library from one end to the other, you devise a clever little method. You take the title of the book, run it through a small computer program, which spits out a shelf number and a slot number on that shelf. This is where you place the book.
The beauty of this program is that later on, when a person comes back in to read the book, you feed the title through the program once more, and get back the same shelf number and slot number that you were originally given, and this is where the book is located.
The program, as others have already mentioned, is called a hash algorithm or hashing, and usually works by taking the data fed into it (the title of the book in this case) and calculates a number from it.For simplicity, let's say that it just converts each letter and symbol into a number, and sums them all up. In reality it's a lot more complicated than that, but let's leave it at that for now.The beauty of such an algorithm is that if you feed the same input into it again and again, it will keep spitting out the same number each time.

What is Hashing?

Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. A true Hashing function must follow this rule:
Hash function should return the same hash code each and every time, when function is applied on same or equal objects. In other words, two equal objects must produce same hash code consistently.
Note: All objects in java inherit a default implementation of hashCode() function defined in Object class. This function produce hash code by typically converting the internal address of the object into an integer, thus producing different hash codes for all different objects.

Characteristics of HashMap 

HashMap use 2 data structure:
  • Hash Use hash value to group elements into slots, control by hash() method of HashMap,
  • linked list (singly)
    Each slot is a singly linked list, their key has the same hash value,
    the slot index is control by indexFor() method of HashMap,
Find value:
First find the slot by hash value, then loop each element in the slot until found or end,
Add value:
First find the slot by hash value,
then try find the value:
* if found, then replace the value,
* if not found, then add a new one to begining of the slot,
Capacity
Capacity is slot size, as element count increase, capacity is larger but liner to element count, and finally equals to size (Integer.MAX_VALUE),
Linked list length:
As element count increase, length is liner to a small constant value, and finally equals to 1,
Speed:
put / get, has O(1) speed, because slot is access via index, and linked list length is very small,
Space:
The slot size increase as element count increase,
but it's empty element are null, so not much space is taking,
Resize:
When resize capacity, it also need to do rehash, this might take a while,


Coding Example of HashMap
public class YasirTest {

public static void main(String[] args){
    HashMap hash=new HashMap<>();
    int i;
    for(i=1;i<=5;i++)
        hash.put(i, "Java Programmer "+i);


    for(i=1;i<=5;i++)
        System.out.println(hash.get(i));
}
}



Friday, 17 October 2014

ArrayList in Java

What is Collection?
A collection is a general term that means something like "a bunch of objects stored in a structured manner". or Simply Collection is also called Container.
Collection is a Java Interface.
A collection represents a group of objects, known as its elements. This framework is provided in the java.util package. Objects can be stored, retrieved, and manipulated as elements of collections.
Collections can be used in various scenarios like storing phone number, Employee names database etc. They are basically used to group multiple elements into a single unit. Some collections allow duplicate elements while others do not. Some collections are ordered and others are not.

Why ArrayList? If you don't know how many items are going to be held in your array, you may be better off using something called an ArrayList. 

What is ArrayList?
An ArrayList is a dynamic data structure(Collection), meaning items can be added and removed from the list. A normal array in java is a static data structure, because you stuck with the initial size of your array but Java ArrayList is a dynamic array, an array that can grow after it is created.


Which Package do you need?
ArrayList is in the "java.util" package and if you want to use this then you should import this package in your code like this
   import java.util.ArrayList;


Hierarchical Structure



The ArrayList class extends AbstractList and implements the List interface.


Why we use ArrayList instead Array?
ArrayList supports dynamic arrays that can grow as needed.
In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold. But, sometimes, you may not know until run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList. In essence, an ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.


How to delcare and use ArrayList?
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");


How to show String ArrayList?
for(String temp:list){
  System.out.println(temp);
}
OR
for(int i=0;i<list.size;i++){
  System.out.println(list.get(i));
}