Scala中的BitSet
ScalaBitSet
集合是唯一元素的集合。
位集是一组表示为64位字的正整数。
语法:
var bitset : Bitset = Bitset(elements...)
在Scala编程语言中,BitSet可以是可变的而且是不变的。
在可变的BitSet中,可以在程序中更改位。使用scala.collection.mutable.BitSet
在不可变的BitSet中,不能在程序中更改位。使用scala.collection.immutable.BitSet
示例1:创建一个新的BitSet
import scala.collection.immutable.BitSet object MyClass { def main(args: Array[String]) { val bitSet: BitSet = BitSet(0, 1, 2, 3) println("Elements of new BitSet are " + bitSet) } }
输出结果
Elements of new BitSet are BitSet(0, 1, 2, 3)
示例2:在BitSet中搜索元素
在Scala中对BitSet的搜索操作非常简单,并且可以在BitSet中传递要搜索的元素,并且它将根据搜索返回true或false。
import scala.collection.immutable.BitSet object MyClass { def main(args: Array[String]) { val bitSet: BitSet = BitSet(0, 13, 25, 39, 50) println("Elements of new BitSet are " + bitSet) println("Element 25 is in the BitSet? " + bitSet(25)) println("Element 34 is in the BitSet? " + bitSet(34)) } }
输出结果
Elements of new BitSet are BitSet(0, 13, 25, 39, 50) Element 25 is in the BitSet? true Element 34 is in the BitSet? false
示例3:将元素添加到BitSet
您可以在Scala的BitSet中添加一个或多个元素。运算符+和++用于在Scala的BitSet中添加单个和多个元素。该操作将需要新的BitSet来保存更新的BitSet。
import scala.collection.immutable.BitSet object MyClass { def main(args: Array[String]) { val bitSet: BitSet = BitSet(0, 13, 25, 39, 50) println("Elements of new BitSet are " + bitSet) println("Adding new elements to BitSet : ") val bitSet2 : BitSet = bitSet + 45 println("Elements of new BitSet are " + bitSet2) println("Adding new elements to BitSet : ") val bitSet3 : BitSet = bitSet2 ++ BitSet(34 , 54) println("Elements of new BitSet are " + bitSet3) } }
输出结果
Elements of new BitSet are BitSet(0, 13, 25, 39, 50) Adding new elements to BitSet : Elements of new BitSet are BitSet(0, 13, 25, 39, 45, 50) Adding new elements to BitSet : Elements of new BitSet are BitSet(0, 13, 25, 34, 39, 45, 50, 54)
示例4:从Scala的BitSet中删除元素
您可以从Scala的BitSet中删除元素。运算符-用于从BitSet中删除元素。该操作将需要新的BitSet来保存更新的BitSet。
import scala.collection.immutable.BitSet object MyClass { def main(args: Array[String]) { val bitSet: BitSet = BitSet(0, 13, 25, 39, 50) println("Elements of new BitSet are " + bitSet) println("Deleting element from BitSet : ") val bitSet2 : BitSet = bitSet - 25 println("Elements of new BitSet are " + bitSet2) } }
输出结果
Elements of new BitSet are BitSet(0, 13, 25, 39, 50) Deleting element from BitSet : Elements of new BitSet are BitSet(0, 13, 39, 50)
示例5:在Scala中创建空的BitSet
也可以在Scala中创建一个空集。empty关键字用于在Scala中创建一个空的BitSet。
import scala.collection.immutable.BitSet object MyClass { def main(args: Array[String]) { val bitSet: BitSet = BitSet.empty println("Elements of new BitSet are " + bitSet) } }
输出结果
Elements of new BitSet are BitSet()