BitSet +() Method in Scala with Example

Here, we will learn about the BitSet +() method in Scala along with syntax and examples.
Submitted by Shivang Yadav, on October 30, 2020

BitSet in Scala is a special collection of positive integers. Scala programming language has a huge library containing a lot of utility functions to help working with data structure easy.

BitSet +() Method

The +() method in Scala is used to add a new non-negative integer to an existing BitSet in Scala.

The new BitSet will contain all elements of the existing BitSet and element that is added to it by the method.

Syntax:

BitSet_Name + (element)

Return type:

The function will return a new BitSet with elements of the previous bitSet plus new elements.

Program 1: Program to illustrate the working of our + method to add an element to a BitSet.

// Scala program to illustrate the working of + method

import scala.collection.immutable.BitSet

object MyObject{
    def main(args: Array[String]) {
        val BitSet1 = BitSet(3, 1, 5, 8, 0)
        println("BitSet initially : " + BitSet1)
        
        // Adding new element using + method     
        val newBitSet = BitSet1 + 32
        println("BitSet after adding new element : " + newBitSet)
    }
}

Output:

BitSet initially : BitSet(0, 1, 3, 5, 8)
BitSet after adding new element : BitSet(0, 1, 3, 5, 8, 32)

Program 2: Program to illustrate the working of our + method to add multiple elements to a BitSet.

// Scala program to illustrate the working of + method

import scala.collection.immutable.BitSet

object MyObject{
    def main(args: Array[String]) {
        val oriBitSet = BitSet(6, 1, 9, 3, 0)
        println("BitSet initially : " + oriBitSet)
        
        // Adding new elements using + method     
        val newBitSet = oriBitSet + 2 + 5
        println("BitSet after adding new element : " + newBitSet)
    }
}

Output:

BitSet initially : BitSet(0, 1, 3, 6, 9)
BitSet after adding new element : BitSet(0, 1, 2, 3, 5, 6, 9)



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.