If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
ArrayList और LinkedList की तरह ही HashSet भी items को store करता है, लेकिन HashSet unique values को ही store करता है। यह भी java.util package की class है।
File : HashSetTest.java
// Import the HashSet class from java.util package.
import java.util.HashSet;
public class HashSetTest {
public static void main(String[] args) {
// create String HashSet object.
HashSet bikes = new HashSet();
bikes.add("Yamaha");
bikes.add("Hero Honda");
bikes.add("Royal Enfield");
System.out.println(bikes);
}
}
[Hero Honda, Royal Enfield, Yamaha]
ध्यान रहे अगर आप duplicate value add हो तो old value remove हो जाएगी।
// Again add same value.
bikes.add("Yamaha");
System.out.println(bikes);
// Output : [Hero Honda, Royal Enfield, Yamaha]
contains() method का use करके ये check कर सकते हैं कि कोई value , create गए HashSet में है या नहीं।
bikes.contains("Yamaha") //Output : true bikes.contains("KTM"); // Output : false
HashSet से किसी item को remove करने के लिए remove() method का use किया जाता है , जिसमे हमें direct item value pass करना पड़ता है। अगर item successfully remove होता है तो true return होगा otherwise false .
bikes.remove("Yamaha");
HashSet से सभी items को remove करने के लिए clear() method का use किया जाता है।
bikes.clear();
HashSet की length / size पता करने के लिए size() method का use किया जाता है।
bikes.size();
HashSet के सभी elements को आप for Loop की help से iterate भी कर सकते हैं।
File : HashSetTest.java
import java.util.HashSet;
public class HashSetTest {
public static void main(String[] args) {
HashSet bikes = new HashSet();
bikes.add("Yamaha");
bikes.add("Hero Honda");
bikes.add("Royal Enfield");
// now iterate.
for (String bike : bikes) {
System.out.println(bike);
}
}
}
Hero Honda Royal Enfield Yamaha
Hi ! My name is Rahul Kumar Rajput. I'm a back end web developer and founder of learnhindituts.com. I live in Uttar Pradesh (UP), India and I love to talk about programming as well as writing technical tutorials and tips that can help to others.
Get connected with me. :) LinkedIn Twitter Instagram Facebook