CodeToConcept
About

java

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

java Tutorials

Introduction
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Java Class & Object
java Method
Java Constructor
Java this keyword
Java super keyword
Java Method Overloading and Overriding
Java Interface
Java Abstract Class
Java Memory Management
Design Patterns
JDBC (Database Connectivity)
Java IDEs

Sample Question

Think it through, then check the tutorial.

CodeToConcept

Quickly learn through simple, structured, and practical coding tutorials. Build your confidence from step zero to real-world experience.

© 2026 CodeToConcept. All rights reserved.

Quick Links

AboutTutorials

Tutorials

JavaHTMLCSS

Support

Privacy PolicyTerms of ServiceContact
GitHubTwitterYouTube

Set in Java

Set is a collection interface for elements that should not appear more than once. Adding an element that is already present does not create another entry. A set has no indexed get operation like a list.

Why Do We Need This?

Suppose we record which topics a learner has completed. Completing Arrays twice should not count as two different completed topics. A set helps keep one entry for each topic.

Main Ideas

ConceptWhat it means
add(value)Returns false if the set already contains an equivalent element
contains(value)Checks whether an element is present
HashSetDoes not promise an iteration order
LinkedHashSetNormally keeps insertion order
TreeSetKeeps a sorted order using natural ordering or a comparator

Simple Working Example

Run this program on its own. All required imports and classes are included.

import java.util.LinkedHashSet;
import java.util.Set;
 
public class HelloWorld {
    public static void main(String[] args) {
        Set<String> completed = new LinkedHashSet<>();
        completed.add("Arrays");
        completed.add("Strings");
        boolean addedAgain = completed.add("Arrays");
        System.out.println(completed);
        System.out.println("Added again: " + addedAgain);
    }
}

Output

[Arrays, Strings]
Added again: false

LinkedHashSet makes the shown iteration order predictable. Hash-based sets use equals and hashCode to identify equal elements. A TreeSet uses its ordering comparison, so that comparison should be consistent with equals to follow the general Set contract.

Topics in This Section

  • HashSet
  • LinkedHashSet
  • TreeSet

Easy Way to Remember

A set expresses uniqueness. Choose its implementation according to the ordering and lookup behavior you need.

See you in next page....??

← StackHashSet →
← StackHashSet →