
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
Importance of HashSet in Java
The HashSet use Hashing to manipulate data. Let us see an example −
Example
import java.util.*; public class Demo{ private final String f_str, l_str; public Demo(String f_str, String l_str){ this.f_str = f_str; this.l_str = l_str; } public boolean equals(Object o){ if (o instanceof Demo) return true; Demo n = (Demo)o; return n.f_str.equals(f_str) && n.l_str.equals(l_str); } public static void main(String[] args){ Set<Demo> my_set = new HashSet<Demo>(); my_set.add(new Demo("Joe", "Goldberg")); System.out.println("Added a new element to the set"); System.out.println("Does the set contain a new instance of the object? "); System.out.println(my_set.contains(new Demo("Jo", "Gold"))); } }
Output
Added a new element to the set Does the set contain a new instance of the object? false
The ‘Demo’ class contains a final string and a constructor. An equals function is defined that checks if an object is an instance of a specific class. It returns true if it is an instance otherwise casts the object to the class and checks using the ’equals’ function. In the main function, a new Set is created and an instance is created. This is checked for using the ‘instanceof’ operator.
- Related Articles
- HashSet in Java
- Get size of HashSet in Java
- The HashSet in Java
- Initializing HashSet in Java
- Initialize HashSet in Java
- Iterate through elements of HashSet in Java
- Find maximum element of HashSet in Java
- Find minimum element of HashSet in Java
- Internal working of Set/HashSet in Java
- Iterate over the elements of HashSet in Java
- Convert array to HashSet in Java
- Add elements to HashSet in Java
- Get Enumeration over HashSet in Java
- Convert HashSet to TreeSet in Java
- How to sort HashSet in Java

Advertisements