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

Vector और Range

एक Vector एक तेज़, अपरिवर्तनीय list है जिसमें आप किसी भी position पर jump कर सकते हैं, और एक Range एक से दस जैसी गिनी हुई sequence है। दोनों numbers और items के साथ काम करने के लिए सुविधाजनक हैं।

In this page:

  1. Vector and Range
Syntax
scala
val vector = Vector(value1, value2, value3)
val range = 1 to 10
val stepped = 1 to 10 by 2

Vector and Range

Vector एक immutable, indexed sequence है जो random access और updates (एक नया Vector return करते हुए) दोनों के लिए अच्छा performance देता है, List के विपरीत जो आगे तेज़ है लेकिन sequence में गहराई से indexed access के लिए धीमा है।

1 to 10 जैसा एक Range, evenly-spaced integers की एक sequence को represent करता है बिना ज़रूरत पड़ने तक हर value को memory में store किए। Ranges अक्सर for loops चलाने या .toList/.toVector से किसी concrete collection में convert करने के लिए उपयोग होती हैं।

Note: जब आपका code elements को आगे से पीछे process करने के बजाय ज़्यादा random (indexed) access करता हो, तब List के बजाय Vector को प्राथमिकता दें।

उदाहरण: Vector and Range

markup
object Main extends App {
  val nums = Vector(1, 2, 3, 4, 5)
  println(nums(2))
  println(nums.updated(2, 99))

  val range = 1 to 10 by 2
  println(range.toList)
}
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. यह उम्मीद करना कि nums.updated(2, 99) nums को बदल देगा, जबकि एक Vector immutable है और यह एक नया vector return करता है।
  2. 1 to 10 by 2 लिखना और result में 10 की उम्मीद करना, जबकि यह 1, 3, 5, 7, 9 देता है।
  3. यह मान लेना कि एक Range हर number store करता है, जबकि यह lazily compute होता है और सिर्फ start, end और step store करता है।
चैप्टर सारांश
  • List, Array, ArrayBuffer, Set, Map, और tuples data को अलग-अलग तरीकों से store करते हैं।
  • head, tail, map, और filter जैसे list operations collections को transform करते हैं।
  • Vector और Range अतिरिक्त sequence types प्रदान करते हैं।
🔒

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.