Tuesday, 2 July 2013

HashSet in JAVA

HashSet extends AbstractSet class and implements Set interface.
hashset does not supports duplicates. So it contains unique elements only.

Following is the hierarchy of HashSet:

Iterable

  | extends
  |

Collection
  
  | extends
  |

 Set

  | implements
  |

AbstractSet

  | extends
  |

HashSet

Example:

/**
 * Set does not allow duplicates but if we are trying to add it will
 * supports but it can not iterate through duplicates and also it check
 * the address not the content for duplication. In below example content
 * is same but are adding three different instances of class
 *
 */
Set set1111 = new HashSet();
  // We have BeanExample implementation below of this class.
BeanExample beanExample = new BeanExample();
beanExample.setUserName("krishna");
beanExample.setPassword("krishna");
set1111.add(beanExample);
BeanExample beanExample1 = new BeanExample();
beanExample1.setUserName("krishna");
beanExample1.setPassword("krishna");
set1111.add(beanExample1);
BeanExample beanExample11 = new BeanExample();
beanExample11.setUserName("krishna");
beanExample11.setPassword("krishna");
set1111.add(beanExample11);

System.out.println("@@@@@@@@@@@@@@@@@@@" + set1111.size());
Iterator iterator111 = set1111.iterator();
while (iterator111.hasNext()) {
// System.out.println(iterator.next());
BeanExample beanExample2 = (BeanExample) iterator111.next();
String userName = beanExample2.getUserName();
System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$" + userName);
}

/**
 * Hash set supports different types of objects. Set support duplicate
 * values while adding but it does not iterate through duplicates.
 */
HashSet stringSet = new HashSet();
String string = "krishna";
Integer integer = new Integer(8);
stringSet.add(integer);
stringSet.add(integer);
stringSet.add(new Integer(9));
System.out.println("###########################" + stringSet.size());
Iterator iterator1111 = stringSet.iterator();

while (iterator1111.hasNext()) {
System.out.println("%%%%%%%%%%%%%%%%%%%%" + iterator1111.next());
}
stringSet.add(string);
stringSet.add(string);
Iterator stringIterator = stringSet.iterator();
while (stringIterator.hasNext()) {
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
+ stringIterator.next());
}

*************************************************

public class BeanExample {

private String userName = null;
private String password = null;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

}

No comments:

Post a Comment