In HashSet, duplicates are not allowed. If we are trying to insert duplicates then we won’t get any compile-time or runtime error and the add() method simply returns false.
We can use 2 ways to print HashSet elements:
- Using the iterator() method to traverse the set elements and printing it.
- Directly printing it using a reference variable.
Method 1: By using Cursor which is Iterator.
- If we want to get objects one by one from the collection then we should go for the cursor.
- We can apply the Iterator concept for any Collection Object and hence it is a Universal Cursor.
- By using Iterator we can perform both read and remove operations.
- We can create an Iterator object by using the iterator method of Collection Interface.
public Iterator iterator(); // Iterator method of Collection Interface.
- Creating an iterator object
Iterator itr = c.iterator(); // where c is any Collection Object like ArrayList,HashSet etc.
null 2 3 5 6
Method 2: We can directly print HashSet elements by using the HashSet object reference variable. It will print the complete HashSet object.
Note: If we do not know the hash code, so you can’t decide the order of insertion.
[A, B, C, D, null, Z, 10]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.