bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Java/Java Data Structures
Java•Java Data Structures

Java Set

Native lesson simulator

Hash map lookup

Hash the key, jump to a bucket, then compare entries there.

Ada -> bucket 20Cy:21Bo:22Ada:3Dee:33

Ada hashes to bucket 2; lookup only scans entries in that bucket.

Java Set Interface

The Set interface is part of the Java Collections Framework and is used to store a collection of unique elements .

Unlike a List , a Set does not allow duplicates , and it does not preserve the order of elements (unless you're using TreeSet or LinkedHashSet ).

Common classes that implement Set

  • HashSet - fast and unordered
  • TreeSet - sorted set
  • LinkedHashSet - ordered by insertion

Tip

Use a Set when you need to store unique values only.

Common Set Methods

MethodDescription
add()Adds an element if it's not already in the set
remove()Removes the element from the set
contains()Checks if the set contains the element
size()Returns the number of elements
clear()Removes all elements

Set vs. List

ListSet
Allows duplicatesDoes not allow duplicates
Maintains orderDoes not guarantee order
Access by indexNo index-based access

Previous

Java List Sorting

Next

Java HashSet

This chapter

Overview
16

Lessons

58m

Read time

1. Java Data Structures2. Java Collections Framework3. Java List4. Java ArrayList5. Java LinkedList6. Java List Sorting7. Java Set8. Java HashSet9. Java TreeSet10. Java LinkedHashSet11. Java Map12. Java HashMap13. Java TreeMap14. Java LinkedHashMap15. Java Iterator16. Java Algorithms

On this page

Java Set InterfaceCommon Set MethodsSet vs. List