← Back to Scala Course | Chapter 6: Collections Basics | Lesson 5 of 8

Set क्या है

एक Set एक bag है जिसमें कभी duplicates नहीं होते, जैसे एक sticker collection जहां आप हर एक की सिर्फ एक copy रखते हैं। पहले से मौजूद चीज़ जोड़ने से कुछ नहीं बदलता।

In this page:

  1. Set
Syntax
scala
val set = Set(value1, value2, value3)
val bigger = set + value
set.contains(value)

Set

एक Set unique elements को बिना किसी तय order और बिना duplicates के store करता है -- पहले से मौजूद element जोड़ने का कोई असर नहीं होता।

Set(1, 2, 3) default रूप से एक immutable set बनाता है; scala.collection.mutable.Set +=/-= को support करने वाला एक mutable version देता है। Sets membership tests और data से duplicates हटाने के लिए आदर्श हैं।

Note: किसी Set में duplicate value जोड़ना चुपचाप कुछ नहीं करता -- पहले से मौजूद element के लिए set का size कभी नहीं बदलता।

उदाहरण: Set

markup
object Main extends App {
  val ids = Set(1, 2, 3)
  val expanded = ids + 2 + 4 // 2 already exists, ignored

  println(expanded)
  println(expanded.contains(3))
  println(expanded.size)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह उम्मीद करना कि एक Set insertion order बनाए रखेगा या duplicates की अनुमति देगा, जबकि duplicates हट जाते हैं और order की गारंटी नहीं है।
  2. ids + 4 का उपयोग करना और ids के बदलने की उम्मीद करना, जबकि यह एक नया Set return करता है क्योंकि default वाला immutable है।
  3. ids(0) जैसे किसी set को index करना, जिसका मतलब पहला element नहीं बल्कि यह जांचना है कि 0 set में है या नहीं।
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.