Showing posts with label HashSet. Show all posts
Showing posts with label HashSet. Show all posts

Saturday, 2 May 2015

#05 How equlas() and hashCode() mehtods work - java.


What are equals and hashCode method do?

Equals and hashCode in Java are two fundamental method which is declared in Object class and part or core Java library. equals() method is used to compare Objects for equality while hashCode is used to generate an integer code corresponding to that object.


In my previous post Easy way to understand HashSet , I described HashSet does not allow duplicate value. 
But think about scenario I have a Student class.

Student POJO Class

I am creating two objects of student.
checking output of equals method

Now look at the output

output of equals method

Wheteher roll numbers ,fname ,lname are same for both objects output is false.
whenever we use == operator for object or equals to method for object. java check whether two reference pointing same memory location or not. if they are not pointing same memory, java consider it as two different objects. 

In this scenario HashSet also add s1 and s2. But it is wrong according to user view.

Here we need to change default behaviour of java equals method. 

So we need to override the equals method of object class and custmize it to our requirement.

I am adding two method in my Student class.

We are adding hashCode method also,because equals object must have same hash code.

Now run the application and look at the output :


It is common practise that whenever we want to add Class object to HashSet, TreeSet,ArrayList, or any java collection we override equals() and hashCode method.

Next ... 
In my next post I will explain functionality of TreeSet.

Hope it will help full.

Thursday, 30 April 2015

#04 Easy way to understand HashSet of Java Collection.

What is HashSet ?

java.util.HashSet implements Set interface interface and it use hash table to store data in memory. Hash Table uses hashing mechanism to store data in memory.  It makes no guarantees as to the iteration order of the set; in particular, it is unordered collection. It does not guarantee that the order will remain constant over time. Later on we will discuss hashing mechanism using by HashSet.

Use Of HashSet

1. HashSet does not allow duplicate elements, So whenever we want to store unique elements we use Hash Set. A common use for a set is to remember which items in a list have 'already been seen' so that they are not processed more than once.

2.  Another advantage of hashing is that it allows the execution time of basic operation, such as add(), contains(), remove(), and size() to remain constant even for large sets.

Different declaration of HashSet

1. Simple Declaration 



2. Declare HashSet of Specific class



3. Declare HashSet with approximate capacity or size


4. Declare HashSet with initial capacity and load factor


Here load factor means when the size of hashset will increase automatically. Suppose initial capacity is 100 and load factor is 0.75. So when set contains 75 elements then size of set will increase, internally new set of more capacity will generate.

5. Declare HashSet with existing collection








Important methods of HashSet

1. boolean add(Object obj)

   It adds object to set if it is not exist



2. boolean contains(Object obj)

   It return true if object exists in set




3. boolean remove(Object obj)

   It remove object if exists and return true, if obj is not exist in set it return false.





4. int size()

   It returns the number of objects in the set.




5. boolean isEmpty()

   It returns true if  set is empty otherwise returns false.


6. void clear()

   This method remove all elements exist in set.



7. Iterator iterator()

This method returns iterator over the elements in the set.








What happens when you try to add duplicate element?

On every add operation hash set interanally call equals() method and hashCode() method. If it find same element already exist in the set. it will not add duplicate.







Can we add null value into set?

This question is mostly asked by beginners. your answer is Yes you can add null, but as per rule you can add only one null value.

  






Complete code : 




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.javasuitor.demo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;

public class HashSetDemo {

 public static void main(String[] args) {
  
  // Declare simple hashset, its default capacity is 16.  
  HashSet hashSet1 = new HashSet();
  
  // Declare hash set of Particular class
  HashSet<String> hashSet2 = new HashSet<String>();
  
  // Declare hash set using initial capacity
  HashSet<String> hashSet3 =  new HashSet<String>(20);
  
  // Declare hash set using initial capacity and Load factor
  HashSet<String> hashSet4 =  new HashSet<String>(20, 0.75f);
  
  ArrayList <String> countryList = new ArrayList<String>();
  countryList.add("India");
  countryList.add("Australia");
  countryList.add("South Africa");
  
  //Declare hash set using pre built Array List
  
  HashSet<String> hashSet5 = new HashSet<String>(countryList);
  
  //Add values in set
  hashSet3.add("Ashok");
  hashSet3.add("Akanksha");
  hashSet3.add("Sumit");
  hashSet3.add("Shivi");
  hashSet3.add("Bhanu");
  
  // Iterator of Set
  Iterator<String> iterator = hashSet3.iterator();
  
  System.out.println("Elements of set");
  while(iterator.hasNext()){
   System.out.println(iterator.next());
  }
  
  // Try to add duplicate element 
  hashSet3.add("Ashok");
  System.out.println("\nSet elements after adding duplicate object\n"+hashSet3);
  
  // HashSet allow to add null value 
  hashSet3.add(null);
  System.out.println("\nSet elements after adding null\n"+hashSet3);
  
  // Check whether the element present in set or not
  System.out.println("\nIs Ashok present in HashSet: "+hashSet3.contains("Ashok"));
  System.out.println("Is Riddhi present in HashSet: "+hashSet3.contains("Riddhi"));
  
  // Remove particular element from set
  hashSet3.remove(null);
  System.out.println("\nSet elements after removing null \n"+hashSet3);
  
  // Get the number of element in hash set  
  System.out.println("\nNumber of elements in hashSet "+hashSet3.size());
  
  // Check whether the HashSet is empty or not
  System.out.println("\nIs hashSet3 is empty : "+hashSet3.isEmpty());
  System.out.println("Is hashSet1 is empty : "+hashSet1.isEmpty());
  
  // Remove all elements from set
  
  hashSet3.clear();
  System.out.println("\n After Clear method values in hashset : "+ hashSet3);
 }
}

Output :



I hope this contents may helps to move one step forward towards learning. Your precious feedback will surely help me to improve contents. Please feel free to contact me.