It is a specialized implementation of the Set interface. It uses the concept of HashTable in Data Structure.
A few important facts about HashSet are as follows:
- It is synchronized.
- It does not allow duplicate values.
- It allows null values.
- Element retrieval order is not the same as insertion.
Hierarchy of HashSet class
It extends AbstractSet and implements Set, Clonable, and Serializable interfaces in Java.
Source code of Item.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.t4b.test;
public class Item {
String name;
int id;
double price;
public Item(String name, int id, double price) {
super();
this.name = name;
this.id = id;
this.price = price;
}
@Override
public String toString() {
return "Item [name=" + name + ", id=" + id + ", price=" + price + "]";
}
Source code of TestMain.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.t4b.test;
import java.util.HashSet;
import java.util.Iterator;
public class TestMain {
public static void main(String[] args) {
HashSet<Item> hashset = new HashSet<Item>();
hashset.add(new Item("Apple", 1, 150.0));
hashset.add(new Item("Grape", 2, 250.0));
hashset.add(new Item("Mango", 3, 10));
hashset.add(new Item("Pine Apple", 4, 100));
Iterator<Item> itr = hashset.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.