Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade For Teachers Spaces Get Certified Upgrade For Teachers Spaces
   ❮     
     ❯   

Java Tutorial

Java HOMEJava IntroJava Get StartedJava SyntaxJava OutputJava CommentsJava VariablesJava Data TypesJava Type CastingJava OperatorsJava StringsJava MathJava BooleansJava If...ElseJava SwitchJava While LoopJava For LoopJava Break/ContinueJava Arrays

Java Methods

Java MethodsJava Method ParametersJava Method OverloadingJava ScopeJava Recursion

Java Classes

Java OOPJava Classes/ObjectsJava Class AttributesJava Class MethodsJava ConstructorsJava this KeywordJava ModifiersJava EncapsulationJava Packages / APIJava InheritanceJava PolymorphismJava super KeywordJava Inner ClassesJava AbstractionJava InterfaceJava AnonymousJava EnumJava User InputJava Date

Java Errors

Java ErrorsJava DebuggingJava ExceptionsJava Multiple ExceptionsJava try-with-resources

Java File Handling

Java FilesJava Create FilesJava Write FilesJava Read FilesJava Delete Files

Java I/O Streams

Java I/O StreamsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriter

Java Data Structures

Java Data StructuresJava CollectionsJava ListJava ArrayListJava LinkedListJava List SortingJava SetJava HashSetJava TreeSetJava LinkedHashSetJava MapJava HashMapJava TreeMapJava LinkedHashMapJava IteratorJava Algorithms

Java Advanced

Java Wrapper ClassesJava GenericsJava AnnotationsJava RegExJava ThreadsJava LambdaJava Advanced Sorting

Java Projects

Java Projects

Java How To's

Java How Tos

Java Reference

Java ReferenceJava KeywordsJava String MethodsJava Math MethodsJava Output MethodsJava Arrays MethodsJava ArrayList MethodsJava LinkedList MethodsJava HashMap MethodsJava Scanner MethodsJava File MethodsJava FileInputStreamJava FileOutputStreamJava BufferedReaderJava BufferedWriterJava Iterator MethodsJava Collections MethodsJava System MethodsJava Errors & Exceptions

Java Examples

Java ExamplesJava CompilerJava ExercisesJava QuizJava ServerJava SyllabusJava Study PlanJava Interview Q&AJava Certificate


JavaHashSet


Java HashSet

AHashSet is a collection of elements where every element isunique.

It is part of thejava.util package and implements theSet interface.


Create a HashSet

Example

Create aHashSet object calledcars that will store strings:

import java.util.HashSet; // Import the HashSet classHashSet<String> cars = new HashSet<String>();

Now you can use methods likeadd(),contains(), andremove() to manage your collection of unique elements.


Add Elements

To add elements to aHashSet, use theadd() method:

Example

// Import the HashSet classimport java.util.HashSet;public class Main {  public static void main(String[] args) {    HashSet<String> cars = new HashSet<String>();    cars.add("Volvo");    cars.add("BMW");    cars.add("Ford");    cars.add("BMW");  // Duplicate    cars.add("Mazda");    System.out.println(cars);  }}

Try it Yourself »

Note: In the example above, even though"BMW" is added twice, it only appears once in the set because sets do not allow duplicate elements.


Check If an Element Exists

To check whether an element exists in aHashSet, use thecontains() method:

Example

cars.contains("Mazda");

Try it Yourself »


Remove an Element

To remove an element, use theremove() method:

Example

cars.remove("Volvo");

Try it Yourself »

To remove all elements, use theclear() method:

Example

cars.clear();

Try it Yourself »



HashSet Size

Usesize() to count how many unique elements are in the set:

Example

cars.size();

Try it Yourself »

Note: Duplicate values are not counted - only unique elements are included in the size.


Loop Through a HashSet

Loop through the elements of anHashSet with afor-each loop:

Example

for (String i : cars) {  System.out.println(i);}

Try it Yourself »


Other Types

Elements in anHashSet are actually objects. In the examples above, we created elements (objects) of type "String". Remember that aString in Java is an object (not a primitive type). To use other types, such asint, you must specify an equivalentwrapper class:Integer. For other primitive types, use:Boolean for boolean,Character for char,Double for double, etc:

Example

Use aHashSet that storesInteger objects:

import java.util.HashSet;public class Main {  public static void main(String[] args) {    // Create a HashSet object called numbers    HashSet<Integer> numbers = new HashSet<Integer>();    // Add values to the set    numbers.add(4);    numbers.add(7);    numbers.add(8);    // Show which numbers between 1 and 10 are in the set    for (int i = 1; i <= 10; i++) {      if (numbers.contains(i)) {        System.out.println(i + " was found in the set.");      } else {        System.out.println(i + " was not found in the set.");      }    }  }}

Try it Yourself »


The var Keyword

From Java 10, you can use thevar keyword to declare aHashSet variable without writing the type twice. The compiler figures out the type from the value you assign.

This makes code shorter,but many developers still use the full type for clarity. Sincevar is valid Java, you may see it in other code, so it's good to know that it exists:

Example

// Without varHashSet<String> cars = new HashSet<String>();// With varvar cars = new HashSet<String>();

Try it Yourself »


The Set Interface

Note: Sometimes you will see bothSet andHashSet in Java code, like this:

import java.util.Set;import java.util.HashSet;Set<String> cars = new HashSet<>();

Try it Yourself »

This means the variable (cars) is declared as aSet (the interface), but it stores aHashSet object (the actual set). SinceHashSet implements theSet interface, this is possible.

It works the same way, but some developers prefer this style because it gives them more flexibility to change the type later.


When Order Matters

In the next chapter, you will learn aboutTreeSet, which stores unique elementsin sorted order.





×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted ourterms of use,cookies andprivacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved.W3Schools is Powered by W3.CSS.


[8]ページ先頭

©2009-2025 Movatter.jp