Scala Library: scala.collection.immutable.HashSet
scala.collection.immutable.HashSet
class HashSet[A] extends AbstractSet[A] with Set[A] with GenericSetTemplate[A, HashSet] with SetLike[A, HashSet[A]] with CustomParallelizable[A, ParHashSet[A]] with Serializable
This class implements immutable sets using a hash trie.
Note: The builder of this hash set may return specialized representations for small sets.
- A
- the type of the elements contained in this hash set.
- Annotations
- @ SerialVersionUID () @ deprecatedInheritance (message =…, since = “2.11.0”)
- Source
- Version
- 2.8
- Since
- 2.3
Type Members
type Self = HashSet[A]
The type implementing this traversable
- Attributes
- protected[this]
- Definition Classes
- TraversableLike
class WithFilter extends FilterMonadic[A, Repr]
A class supporting filtered operations. Instances of this class are returned by
method withFilter
.
- Definition Classes
- TraversableLike
Value Members From scala.Function1
def andThen[A](g: (Boolean) ⇒ A): (A) ⇒ A
Composes two instances of Function1 in a new Function1, with this function applied first.
- A
- the result type of function
g
- the result type of function
- g
- a function R => A
- returns
- a new function
f
such thatf(x) == g(apply(x))
- a new function
- Definition Classes
- Function1
- Annotations
- @ unspecialized ()
(defined at scala.Function1)
def compose[A](g: (A) ⇒ A): (A) ⇒ Boolean
Composes two instances of Function1 in a new Function1, with this function applied last.
- A
- the type to which function
g
can be applied
- the type to which function
- g
- a function A => T1
- returns
- a new function
f
such thatf(x) == apply(g(x))
- a new function
- Definition Classes
- Function1
- Annotations
- @ unspecialized ()
(defined at scala.Function1)
Value Members From scala.collection.CustomParallelizable
def parCombiner: Combiner[A, ParHashSet[A]]
The default par
implementation uses the combiner provided by this method to
create a new parallel collection.
- returns
- a combiner for the parallel collection of type
ParRepr
- a combiner for the parallel collection of type
- Attributes
- protected[this]
- Definition Classes
- CustomParallelizable → Parallelizable
(defined at scala.collection.CustomParallelizable)
Value Members From scala.collection.GenSetLike
def &(that: GenSet[A]): HashSet[A]
Computes the intersection between this set and another set.
Note: Same as intersect
.
- that
- the set to intersect with.
- returns
- a new set consisting of all elements that are both in this set and in the
given set
that
.
- a new set consisting of all elements that are both in this set and in the
given set
- Definition Classes
- GenSetLike
(defined at scala.collection.GenSetLike)
def &~(that: GenSet[A]): HashSet[A]
The difference of this set and another set.
Note: Same as diff
.
- that
- the set of elements to exclude.
- returns
- a set containing those elements of this set that are not also contained in
the given set
that
.
- a set containing those elements of this set that are not also contained in
the given set
- Definition Classes
- GenSetLike
(defined at scala.collection.GenSetLike)
def apply(elem: A): Boolean
Tests if some element is contained in this set.
This method is equivalent to contains
. It allows sets to be interpreted as
predicates.
- elem
- the element to test for membership.
- returns
true
ifelem
is contained in this set,false
otherwise.
- Definition Classes
- GenSetLike → Function1
(defined at scala.collection.GenSetLike)
def equals(that: Any): Boolean
Compares this set with another object for equality.
Note: This operation contains an unchecked cast: if that
is a set, it will
assume with an unchecked cast that it has the same element type as this set. Any
subsequent ClassCastException is treated as a false
result.
- that
- the other object
- returns
true
ifthat
is a set which contains the same elements as this set.
- Definition Classes
- GenSetLike → Equals → AnyRef → Any
(defined at scala.collection.GenSetLike)
def |(that: GenSet[A]): HashSet[A]
Computes the union between this set and another set.
Note: Same as union
.
- that
- the set to form the union with.
- returns
- a new set consisting of all elements that are in this set or in the given
set
that
.
- a new set consisting of all elements that are in this set or in the given
set
- Definition Classes
- GenSetLike
(defined at scala.collection.GenSetLike)
Value Members From scala.collection.IterableLike
def canEqual(that: Any): Boolean
Method called from equality methods, so that user-defined subclasses can refuse to be equal to other collections of the same kind.
- that
- The object with which this iterable collection should be compared
- returns
true
, if this iterable collection can possibly equalthat
,false
otherwise. The test takes into consideration only the run-time types of objects but ignores their elements.
- Definition Classes
- IterableLike → Equals
(defined at scala.collection.IterableLike)
def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Unit
[use case]
Copies the elements of this immutable hash set to an array. Fills the given
array xs
with at most len
elements of this immutable hash set, starting at
position start
. Copying will stop once either the end of the current
immutable hash set is reached, or the end of the target array is reached, or
len
elements have been copied.
- xs
- the array to fill.
- start
- the starting index.
- len
- the maximal number of elements to copy.
- Definition Classes
- IterableLike → TraversableLike → TraversableOnce → GenTraversableOnce
(defined at scala.collection.IterableLike)
def drop(n: Int): HashSet[A]
Selects all elements except first n ones.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- n
- the number of elements to drop from this iterable collection.
- returns
- a iterable collection consisting of all elements of this iterable collection
except the first
n
ones, or else the empty iterable collection, if this iterable collection has less thann
elements.
- a iterable collection consisting of all elements of this iterable collection
except the first
- Definition Classes
- IterableLike → TraversableLike → GenTraversableLike
(defined at scala.collection.IterableLike)
def dropRight(n: Int): HashSet[A]
Selects all elements except last n ones.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- n
- The number of elements to take
- returns
- a iterable collection consisting of all elements of this iterable collection
except the last
n
ones, or else the empty iterable collection, if this iterable collection has less thann
elements.
- a iterable collection consisting of all elements of this iterable collection
except the last
- Definition Classes
- IterableLike
(defined at scala.collection.IterableLike)
def exists(p: (A) ⇒ Boolean): Boolean
Tests whether a predicate holds for at least one element of this iterable collection.
Note: may not terminate for infinite-sized collections.
- p
- the predicate used to test elements.
- returns
false
if this iterable collection is empty, otherwisetrue
if the given predicatep
holds for some of the elements of this iterable collection, otherwisefalse
- Definition Classes
- IterableLike → TraversableLike → TraversableOnce → GenTraversableOnce
(defined at scala.collection.IterableLike)
def find(p: (A) ⇒ Boolean): Option[A]
Finds the first element of the iterable collection satisfying a predicate, if any.
Note: may not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- p
- the predicate used to test elements.
- returns
- an option value containing the first element in the iterable collection that
satisfies
p
, orNone
if none exists.
- an option value containing the first element in the iterable collection that
satisfies
- Definition Classes
- IterableLike → TraversableLike → TraversableOnce → GenTraversableOnce
(defined at scala.collection.IterableLike)
def foldRight[B](z: B)(op: (A, B) ⇒ B): B
Applies a binary operator to all elements of this iterable collection and a start value, going right to left.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered. or the operator is associative and commutative.
- B
- the result type of the binary operator.
- z
- the start value.
- op
- the binary operator.
- returns
- the result of inserting
op
between consecutive elements of this iterable collection, going right to left with the start valuez
on the right:
- the result of inserting
op(x_1, op(x_2, ... op(x_n, z)...))
where `x1, ..., xn` are the elements of this iterable collection. Returns
`z` if this iterable collection is empty.
- Definition Classes
- IterableLike → TraversableOnce → GenTraversableOnce
(defined at scala.collection.IterableLike)
def forall(p: (A) ⇒ Boolean): Boolean
Tests whether a predicate holds for all elements of this iterable collection.
Note: may not terminate for infinite-sized collections.
- p
- the predicate used to test elements.
- returns
true
if this iterable collection is empty or the given predicatep
holds for all elements of this iterable collection, otherwisefalse
.
- Definition Classes
- IterableLike → TraversableLike → TraversableOnce → GenTraversableOnce
(defined at scala.collection.IterableLike)
def grouped(size: Int): Iterator[HashSet[A]]
Partitions elements in fixed size iterable collections.
- size
- the number of elements per group
- returns
- An iterator producing iterable collections of size
size
, except the last will be less than sizesize
if the elements don’t divide evenly.
- An iterator producing iterable collections of size
- Definition Classes
- IterableLike
- See also
- scala.collection.Iterator, method
grouped
- scala.collection.Iterator, method
(defined at scala.collection.IterableLike)
def reduceRight[B >: A](op: (A, B) ⇒ B): B
Applies a binary operator to all elements of this iterable collection, going right to left.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered. or the operator is associative and commutative.
- B
- the result type of the binary operator.
- op
- the binary operator.
- returns
- the result of inserting
op
between consecutive elements of this iterable collection, going right to left:
- the result of inserting
op(x_1, op(x_2, ..., op(x_{n-1}, x_n)...))
where `x1, ..., xn` are the elements of this iterable collection.
- Definition Classes
- IterableLike → TraversableOnce → GenTraversableOnce
- Exceptions thrown
- UnsupportedOperationException if this iterable collection is empty.
(defined at scala.collection.IterableLike)
def sameElements[B >: A](that: GenIterable[B]): Boolean
[use case]
Checks if the other iterable collection contains the same elements in the same order as this immutable hash set.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- that
- the collection to compare with.
- returns
true
, if both collections contain the same elements in the same order,false
otherwise.
- Definition Classes
- IterableLike → GenIterableLike
(defined at scala.collection.IterableLike)
def slice(from: Int, until: Int): HashSet[A]
Selects an interval of elements. The returned collection is made up of all
elements x
which satisfy the invariant:
from <= indexOf(x) < until
Note: might return different results for different runs, unless the underlying collection type is ordered.
- returns
- a iterable collection containing the elements greater than or equal to index
from
extending up to (but not including) indexuntil
of this iterable collection.
- a iterable collection containing the elements greater than or equal to index
- Definition Classes
- IterableLike → TraversableLike → GenTraversableLike
(defined at scala.collection.IterableLike)
def sliding(size: Int): Iterator[HashSet[A]]
Groups elements in fixed size blocks by passing a “sliding window” over them (as opposed to partitioning them, as is done in grouped.) “Sliding window” step is 1 by default.
- size
- the number of elements per group
- returns
- An iterator producing iterable collections of size
size
, except the last and the only element will be truncated if there are fewer elements than size.
- An iterator producing iterable collections of size
- Definition Classes
- IterableLike
- See also
- scala.collection.Iterator, method
sliding
- scala.collection.Iterator, method
(defined at scala.collection.IterableLike)
def sliding(size: Int, step: Int): Iterator[HashSet[A]]
Groups elements in fixed size blocks by passing a “sliding window” over them (as opposed to partitioning them, as is done in grouped.)
- size
- the number of elements per group
- step
- the distance between the first elements of successive groups
- returns
- An iterator producing iterable collections of size
size
, except the last and the only element will be truncated if there are fewer elements than size.
- An iterator producing iterable collections of size
- Definition Classes
- IterableLike
- See also
- scala.collection.Iterator, method
sliding
- scala.collection.Iterator, method
(defined at scala.collection.IterableLike)
def take(n: Int): HashSet[A]
Selects first n elements.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- n
- the number of elements to take from this iterable collection.
- returns
- a iterable collection consisting only of the first
n
elements of this iterable collection, or else the whole iterable collection, if it has less thann
elements.
- a iterable collection consisting only of the first
- Definition Classes
- IterableLike → TraversableLike → GenTraversableLike
(defined at scala.collection.IterableLike)
def takeRight(n: Int): HashSet[A]
Selects last n elements.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- n
- the number of elements to take
- returns
- a iterable collection consisting only of the last
n
elements of this iterable collection, or else the whole iterable collection, if it has less thann
elements.
- a iterable collection consisting only of the last
- Definition Classes
- IterableLike
(defined at scala.collection.IterableLike)
def takeWhile(p: (A) ⇒ Boolean): HashSet[A]
Takes longest prefix of elements that satisfy a predicate.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- returns
- the longest prefix of this iterable collection whose elements all satisfy
the predicate
p
.
- the longest prefix of this iterable collection whose elements all satisfy
the predicate
- Definition Classes
- IterableLike → TraversableLike → GenTraversableLike
(defined at scala.collection.IterableLike)
def thisCollection: collection.Iterable[A]
The underlying collection seen as an instance of Iterable
. By default this is
implemented as the current collection object itself, but this can be overridden.
- Attributes
- protected[this]
- Definition Classes
- IterableLike → TraversableLike
(defined at scala.collection.IterableLike)
def toCollection(repr: HashSet[A]): collection.Iterable[A]
A conversion from collections of type Repr
to Iterable
objects. By default
this is implemented as just a cast, but this can be overridden.
- Attributes
- protected[this]
- Definition Classes
- IterableLike → TraversableLike
(defined at scala.collection.IterableLike)
def toIterable: collection.Iterable[A]
Returns this iterable collection as an iterable collection.
A new collection will not be built; lazy collections will stay lazy.
Note: will not terminate for infinite-sized collections.
- returns
- an
Iterable
containing all elements of this iterable collection.
- an
- Definition Classes
- IterableLike → TraversableOnce → GenTraversableOnce
(defined at scala.collection.IterableLike)
def toStream: Stream[A]
Converts this iterable collection to a stream.
- returns
- a stream containing all elements of this iterable collection.
- Definition Classes
- IterableLike → TraversableLike → GenTraversableOnce
(defined at scala.collection.IterableLike)
def view(from: Int, until: Int): IterableView[A, HashSet[A]]
Creates a non-strict view of a slice of this iterable collection.
Note: the difference between view
and slice
is that view
produces a view
of the current iterable collection, whereas slice
produces a new iterable
collection.
Note: view(from, to)
is equivalent to view.slice(from, to)
Note: might return different results for different runs, unless the underlying collection type is ordered.
- from
- the index of the first element of the view
- until
- the index of the element following the view
- returns
- a non-strict view of a slice of this iterable collection, starting at index
from
and extending up to (but not including) indexuntil
.
- a non-strict view of a slice of this iterable collection, starting at index
- Definition Classes
- IterableLike → TraversableLike
(defined at scala.collection.IterableLike)
def view: IterableView[A, HashSet[A]]
Creates a non-strict view of this iterable collection.
- returns
- a non-strict view of this iterable collection.
- Definition Classes
- IterableLike → TraversableLike
(defined at scala.collection.IterableLike)
def zipAll[B, A1 >: A, That](that: GenIterable[B], thisElem: A1, thatElem: B)(implicit bf: CanBuildFrom[HashSet[A], (A1, B), That]): That
[use case]
Returns a immutable hash set formed from this immutable hash set and another iterable collection by combining corresponding elements in pairs. If one of the two collections is shorter than the other, placeholder elements are used to extend the shorter collection to the length of the longer.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- B
- the type of the second half of the returned pairs
- that
- The iterable providing the second half of each result pair
- thisElem
- the element to be used to fill up the result if this immutable hash set is
shorter than
that
.
- the element to be used to fill up the result if this immutable hash set is
shorter than
- thatElem
- the element to be used to fill up the result if
that
is shorter than this immutable hash set.
- the element to be used to fill up the result if
- returns
- a new immutable hash set containing pairs consisting of corresponding
elements of this immutable hash set and
that
. The length of the returned collection is the maximum of the lengths of this immutable hash set andthat
. If this immutable hash set is shorter thanthat
,thisElem
values are used to pad the result. Ifthat
is shorter than this immutable hash set,thatElem
values are used to pad the result.
- a new immutable hash set containing pairs consisting of corresponding
elements of this immutable hash set and
- Definition Classes
- IterableLike → GenIterableLike
(defined at scala.collection.IterableLike)
def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[HashSet[A], (A1, Int), That]): That
[use case]
Zips this immutable hash set with its indices.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- returns
- A new immutable hash set containing pairs consisting of all elements of this
immutable hash set paired with their index. Indices start at
0
.
- A new immutable hash set containing pairs consisting of all elements of this
immutable hash set paired with their index. Indices start at
- Definition Classes
- IterableLike → GenIterableLike
Example:
List("a", "b", "c").zipWithIndex = List(("a", 0), ("b", 1), ("c", 2))
(defined at scala.collection.IterableLike)
def zip[A1 >: A, B, That](that: GenIterable[B])(implicit bf: CanBuildFrom[HashSet[A], (A1, B), That]): That
[use case]
Returns a immutable hash set formed from this immutable hash set and another iterable collection by combining corresponding elements in pairs. If one of the two collections is longer than the other, its remaining elements are ignored.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- B
- the type of the second half of the returned pairs
- that
- The iterable providing the second half of each result pair
- returns
- a new immutable hash set containing pairs consisting of corresponding
elements of this immutable hash set and
that
. The length of the returned collection is the minimum of the lengths of this immutable hash set andthat
.
- a new immutable hash set containing pairs consisting of corresponding
elements of this immutable hash set and
- Definition Classes
- IterableLike → GenIterableLike
(defined at scala.collection.IterableLike)
Value Members From scala.collection.SetLike
def ++(elems: GenTraversableOnce[A]): HashSet[A]
Creates a new set by adding all elements contained in another collection to this set, omitting duplicates.
This method takes a collection of elements and adds all elements, omitting duplicates, into set.
Example:
scala> val a = Set(1, 2) ++ Set(2, "a")
a: scala.collection.immutable.Set[Any] = Set(1, 2, a)
- elems
- the collection containing the elements to add.
- returns
- a new set with the given elements added, omitting duplicates.
- Definition Classes
- SetLike
(defined at scala.collection.SetLike)
def map[B, That](f: (A) ⇒ B)(implicit bf: CanBuildFrom[HashSet[A], B, That]): That
[use case]
Builds a new collection by applying a function to all elements of this immutable hash set.
- B
- the element type of the returned collection.
- f
- the function to apply to each element.
- returns
- a new immutable hash set resulting from applying the given function
f
to each element of this immutable hash set and collecting the results.
- a new immutable hash set resulting from applying the given function
- Definition Classes
- SetLike → TraversableLike → GenTraversableLike → FilterMonadic
(defined at scala.collection.SetLike)
def newBuilder: Builder[A, HashSet[A]]
A common implementation of newBuilder
for all sets in terms of empty
.
Overridden for mutable sets in mutable.SetLike
.
- Attributes
- protected[this]
- Definition Classes
- SetLike → TraversableLike → HasNewBuilder
(defined at scala.collection.SetLike)
def subsets(): Iterator[HashSet[A]]
An iterator over all subsets of this set.
- returns
- the iterator.
- Definition Classes
- SetLike
(defined at scala.collection.SetLike)
def subsets(len: Int): Iterator[HashSet[A]]
An iterator over all subsets of this set of the given size. If the requested size is impossible, an empty iterator is returned.
- len
- the size of the subsets.
- returns
- the iterator.
- Definition Classes
- SetLike
(defined at scala.collection.SetLike)
def toBuffer[A1 >: A]: Buffer[A1]
Uses the contents of this set to create a new mutable buffer.
- returns
- a buffer containing all elements of this set.
- Definition Classes
- SetLike → TraversableOnce → GenTraversableOnce
(defined at scala.collection.SetLike)
def toSeq: collection.Seq[A]
Converts this set to a sequence. As with toIterable
, it’s lazy in this
default implementation, as this TraversableOnce
may be lazy and unevaluated.
- returns
- a sequence containing all elements of this set.
- Definition Classes
- SetLike → TraversableOnce → GenTraversableOnce
(defined at scala.collection.SetLike)
Value Members From scala.collection.TraversableLike
def ++:[B >: A, That](that: collection.Traversable[B])(implicit bf: CanBuildFrom[HashSet[A], B, That]): That
As with ++
, returns a new collection containing the elements from the left
operand followed by the elements from the right operand.
It differs from ++
in that the right operand determines the type of the
resulting collection rather than the left one. Mnemonic: the COLon is on the
side of the new COLlection type.
Example:
scala> val x = List(1)
x: List[Int] = List(1)
scala> val y = LinkedList(2)
y: scala.collection.mutable.LinkedList[Int] = LinkedList(2)
scala> val z = x ++: y
z: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2)
This overload exists because: for the implementation of ++:
we should reuse
that of ++
because many collections override it with more efficient versions.
Since TraversableOnce
has no ++
method, we have to implement that directly,
but Traversable
and down can use the overload.
- B
- the element type of the returned collection.
- That
- the class of the returned collection. Where possible,
That
is the same class as the current collection classRepr
, but this depends on the element typeB
being admissible for that class, which means that an implicit instance of typeCanBuildFrom[Repr, B, That]
is found.
- the class of the returned collection. Where possible,
- that
- the traversable to append.
- bf
- an implicit value of class
CanBuildFrom
which determines the result classThat
from the current representation typeRepr
and and the new element typeB
.
- an implicit value of class
- returns
- a new collection of type
That
which contains all elements of this traversable collection followed by all elements ofthat
.
- a new collection of type
- Definition Classes
- TraversableLike
(defined at scala.collection.TraversableLike)
def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[HashSet[A], B, That]): That
[use case]
As with ++
, returns a new collection containing the elements from the left
operand followed by the elements from the right operand.
It differs from ++
in that the right operand determines the type of the
resulting collection rather than the left one. Mnemonic: the COLon is on the
side of the new COLlection type.
Example:
scala> val x = List(1)
x: List[Int] = List(1)
scala> val y = LinkedList(2)
y: scala.collection.mutable.LinkedList[Int] = LinkedList(2)
scala> val z = x ++: y
z: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2)
- B
- the element type of the returned collection.
- that
- the traversable to append.
- returns
- a new immutable hash set which contains all elements of this immutable hash
set followed by all elements of
that
.
- a new immutable hash set which contains all elements of this immutable hash
set followed by all elements of
- Definition Classes
- TraversableLike
(defined at scala.collection.TraversableLike)
def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[HashSet[A], B, That]): That
[use case]
Returns a new immutable hash set containing the elements from the left hand operand followed by the elements from the right hand operand. The element type of the immutable hash set is the most specific superclass encompassing the element types of the two operands.
Example:
scala> val a = List(1)
a: List[Int] = List(1)
scala> val b = List(2)
b: List[Int] = List(2)
scala> val c = a ++ b
c: List[Int] = List(1, 2)
scala> val d = List('a')
d: List[Char] = List(a)
scala> val e = c ++ d
e: List[AnyVal] = List(1, 2, a)
- B
- the element type of the returned collection.
- that
- the traversable to append.
- returns
- a new immutable hash set which contains all elements of this immutable hash
set followed by all elements of
that
.
- a new immutable hash set which contains all elements of this immutable hash
set followed by all elements of
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[HashSet[A], B, That]): That
[use case]
Builds a new collection by applying a partial function to all elements of this immutable hash set on which the function is defined.
- B
- the element type of the returned collection.
- pf
- the partial function which filters and maps the immutable hash set.
- returns
- a new immutable hash set resulting from applying the given partial function
pf
to each element on which it is defined and collecting the results. The order of the elements is preserved.
- a new immutable hash set resulting from applying the given partial function
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def dropWhile(p: (A) ⇒ Boolean): HashSet[A]
Drops longest prefix of elements that satisfy a predicate.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- returns
- the longest suffix of this traversable collection whose first element does
not satisfy the predicate
p
.
- the longest suffix of this traversable collection whose first element does
not satisfy the predicate
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def flatMap[B, That](f: (A) ⇒ GenTraversableOnce[B])(implicit bf: CanBuildFrom[HashSet[A], B, That]): That
[use case]
Builds a new collection by applying a function to all elements of this immutable hash set and using the elements of the resulting collections.
For example:
def getWords(lines: Seq[String]): Seq[String] = lines flatMap (line => line split "\\W+")
The type of the resulting collection is guided by the static type of immutable hash set. This might cause unexpected results sometimes. For example:
// lettersOf will return a Seq[Char] of likely repeated letters, instead of a Set
def lettersOf(words: Seq[String]) = words flatMap (word => word.toSet)
// lettersOf will return a Set[Char], not a Seq
def lettersOf(words: Seq[String]) = words.toSet flatMap (word => word.toSeq)
// xs will be an Iterable[Int]
val xs = Map("a" -> List(11,111), "b" -> List(22,222)).flatMap(_._2)
// ys will be a Map[Int, Int]
val ys = Map("a" -> List(1 -> 11,1 -> 111), "b" -> List(2 -> 22,2 -> 222)).flatMap(_._2)
- B
- the element type of the returned collection.
- f
- the function to apply to each element.
- returns
- a new immutable hash set resulting from applying the given collection-valued
function
f
to each element of this immutable hash set and concatenating the results.
- a new immutable hash set resulting from applying the given collection-valued
function
- Definition Classes
- TraversableLike → GenTraversableLike → FilterMonadic
(defined at scala.collection.TraversableLike)
def groupBy[K](f: (A) ⇒ K): Map[K, HashSet[A]]
Partitions this traversable collection into a map of traversable collections according to some discriminator function.
Note: this method is not re-implemented by views. This means when applied to a view it will always force the view and return a new traversable collection.
- K
- the type of keys returned by the discriminator function.
- f
- the discriminator function.
- returns
- A map from keys to traversable collections such that the following invariant holds:
(xs groupBy f)(k) = xs filter (x => f(x) == k)
That is, every key `k` is bound to a traversable collection of those
elements `x` for which `f(x)` equals `k` .
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def init: HashSet[A]
Selects all elements except the last.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- returns
- a traversable collection consisting of all elements of this traversable collection except the last one.
- Definition Classes
- TraversableLike → GenTraversableLike
- Exceptions thrown
- UnsupportedOperationException if the traversable collection is empty.
(defined at scala.collection.TraversableLike)
def inits: Iterator[HashSet[A]]
Iterates over the inits of this traversable collection. The first value will be
this traversable collection and the final one will be an empty traversable
collection, with the intervening values the results of successive applications
of init
.
- returns
- an iterator over all the inits of this traversable collection
- Definition Classes
- TraversableLike
Example:
List(1,2,3).inits = Iterator(List(1,2,3), List(1,2), List(1), Nil)
(defined at scala.collection.TraversableLike)
def partition(p: (A) ⇒ Boolean): (HashSet[A], HashSet[A])
Partitions this traversable collection in two traversable collections according to a predicate.
- p
- the predicate on which to partition.
- returns
- a pair of traversable collections: the first traversable collection consists
of all elements that satisfy the predicate
p
and the second traversable collection consists of all elements that don’t. The relative order of the elements in the resulting traversable collections is the same as in the original traversable collection.
- a pair of traversable collections: the first traversable collection consists
of all elements that satisfy the predicate
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def repr: HashSet[A]
The collection of type traversable collection underlying this TraversableLike
object. By default this is implemented as the TraversableLike
object itself,
but this can be overridden.
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def scanLeft[B, That](z: B)(op: (B, A) ⇒ B)(implicit bf: CanBuildFrom[HashSet[A], B, That]): That
Produces a collection containing cumulative results of applying the operator going left to right.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- B
- the type of the elements in the resulting collection
- That
- the actual type of the resulting collection
- z
- the initial value
- op
- the binary operator applied to the intermediate result and the element
- bf
- an implicit value of class
CanBuildFrom
which determines the result classThat
from the current representation typeRepr
and and the new element typeB
.
- an implicit value of class
- returns
- collection with intermediate results
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def scanRight[B, That](z: B)(op: (A, B) ⇒ B)(implicit bf: CanBuildFrom[HashSet[A], B, That]): That
Produces a collection containing cumulative results of applying the operator going right to left. The head of the collection is the last cumulative result.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered.
Example:
List(1, 2, 3, 4).scanRight(0)(_ + _) == List(10, 9, 7, 4, 0)
- B
- the type of the elements in the resulting collection
- That
- the actual type of the resulting collection
- z
- the initial value
- op
- the binary operator applied to the intermediate result and the element
- bf
- an implicit value of class
CanBuildFrom
which determines the result classThat
from the current representation typeRepr
and and the new element typeB
.
- an implicit value of class
- returns
- collection with intermediate results
- Definition Classes
- TraversableLike → GenTraversableLike
- Annotations
- @migration
- Migration
- (Changed in version 2.9.0) The behavior of
scanRight
has changed. The previous behavior can be reproduced with scanRight.reverse.
- (Changed in version 2.9.0) The behavior of
(defined at scala.collection.TraversableLike)
def scan[B >: A, That](z: B)(op: (B, B) ⇒ B)(implicit cbf: CanBuildFrom[HashSet[A], B, That]): That
Computes a prefix scan of the elements of the collection.
Note: The neutral element z
may be applied more than once.
- B
- element type of the resulting collection
- That
- type of the resulting collection
- z
- neutral element for the operator
op
- neutral element for the operator
- op
- the associative operator for the scan
- cbf
- combiner factory which provides a combiner
- returns
- a new traversable collection containing the prefix scan of the elements in this traversable collection
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def span(p: (A) ⇒ Boolean): (HashSet[A], HashSet[A])
Splits this traversable collection into a prefix/suffix pair according to a predicate.
Note: c span p
is equivalent to (but possibly more efficient than)
(c takeWhile p, c dropWhile p)
, provided the evaluation of the predicate
p
does not cause any side-effects.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- returns
- a pair consisting of the longest prefix of this traversable collection whose
elements all satisfy
p
, and the rest of this traversable collection.
- a pair consisting of the longest prefix of this traversable collection whose
elements all satisfy
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def splitAt(n: Int): (HashSet[A], HashSet[A])
Splits this traversable collection into two at a given position. Note:
c splitAt n
is equivalent to (but possibly more efficient than)
(c take n, c drop n)
.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- n
- the position at which to split.
- returns
- a pair of traversable collections consisting of the first
n
elements of this traversable collection, and the other elements.
- a pair of traversable collections consisting of the first
- Definition Classes
- TraversableLike → GenTraversableLike
(defined at scala.collection.TraversableLike)
def tail: HashSet[A]
Selects all elements except the first.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- returns
- a traversable collection consisting of all elements of this traversable collection except the first one.
- Definition Classes
- TraversableLike → GenTraversableLike
- Exceptions thrown
UnsupportedOperationException
if the traversable collection is empty.
(defined at scala.collection.TraversableLike)
def tails: Iterator[HashSet[A]]
Iterates over the tails of this traversable collection. The first value will be
this traversable collection and the final one will be an empty traversable
collection, with the intervening values the results of successive applications
of tail
.
- returns
- an iterator over all the tails of this traversable collection
- Definition Classes
- TraversableLike
Example:
List(1,2,3).tails = Iterator(List(1,2,3), List(2,3), List(3), Nil)
(defined at scala.collection.TraversableLike)
def toTraversable: collection.Traversable[A]
Converts this traversable collection to an unspecified Traversable. Will return the same collection if this instance is already Traversable.
Note: will not terminate for infinite-sized collections.
- returns
- a Traversable containing all elements of this traversable collection.
- Definition Classes
- TraversableLike → TraversableOnce → GenTraversableOnce
- Annotations
- @ deprecatedOverriding (message =…, since = “2.11.0”)
(defined at scala.collection.TraversableLike)
def withFilter(p: (A) ⇒ Boolean): FilterMonadic[A, HashSet[A]]
Creates a non-strict filter of this traversable collection.
Note: the difference between c filter p
and c withFilter p
is that the
former creates a new collection, whereas the latter only restricts the domain of
subsequent map
, flatMap
, foreach
, and withFilter
operations.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- p
- the predicate used to test elements.
- returns
- an object of class
WithFilter
, which supportsmap
,flatMap
,foreach
, andwithFilter
operations. All these operations apply to those elements of this traversable collection which satisfy the predicatep
.
- an object of class
- Definition Classes
- TraversableLike → FilterMonadic
(defined at scala.collection.TraversableLike)
Value Members From scala.collection.TraversableOnce
def /:[B](z: B)(op: (B, A) ⇒ B): B
Applies a binary operator to a start value and all elements of this traversable or iterator, going left to right.
Note: /:
is alternate syntax for foldLeft
; z /: xs
is the same as
xs foldLeft z
.
Examples:
Note that the folding function used to compute b is equivalent to that used to compute c.
scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)
scala> val b = (5 /: a)(_+_)
b: Int = 15
scala> val c = (5 /: a)((x,y) => x + y)
c: Int = 15
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.
- B
- the result type of the binary operator.
- z
- the start value.
- op
- the binary operator.
- returns
- the result of inserting
op
between consecutive elements of this traversable or iterator, going left to right with the start valuez
on the left:
- the result of inserting
op(...op(op(z, x_1), x_2), ..., x_n)
where `x1, ..., xn` are the elements of this traversable or iterator.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def :\[B](z: B)(op: (A, B) ⇒ B): B
Applies a binary operator to all elements of this traversable or iterator and a start value, going right to left.
Note: :\
is alternate syntax for foldRight
; xs :\ z
is the same as
xs foldRight z
.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.
Examples:
Note that the folding function used to compute b is equivalent to that used to compute c.
scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)
scala> val b = (a :\ 5)(_+_)
b: Int = 15
scala> val c = (a :\ 5)((x,y) => x + y)
c: Int = 15
- B
- the result type of the binary operator.
- z
- the start value
- op
- the binary operator
- returns
- the result of inserting
op
between consecutive elements of this traversable or iterator, going right to left with the start valuez
on the right:
- the result of inserting
op(x_1, op(x_2, ... op(x_n, z)...))
where `x1, ..., xn` are the elements of this traversable or iterator.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def addString(b: StringBuilder): StringBuilder
Appends all elements of this traversable or iterator to a string builder. The
written text consists of the string representations (w.r.t. the method
toString
) of all elements of this traversable or iterator without any
separator string.
Example:
scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)
scala> val b = new StringBuilder()
b: StringBuilder =
scala> val h = a.addString(b)
h: StringBuilder = 1234
- b
- the string builder to which elements are appended.
- returns
- the string builder
b
to which elements were appended.
- the string builder
- Definition Classes
- TraversableOnce
(defined at scala.collection.TraversableOnce)
def addString(b: StringBuilder, sep: String): StringBuilder
Appends all elements of this traversable or iterator to a string builder using a
separator string. The written text consists of the string representations
(w.r.t. the method toString
) of all elements of this traversable or iterator,
separated by the string sep
.
Example:
scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)
scala> val b = new StringBuilder()
b: StringBuilder =
scala> a.addString(b, ", ")
res0: StringBuilder = 1, 2, 3, 4
- b
- the string builder to which elements are appended.
- sep
- the separator string.
- returns
- the string builder
b
to which elements were appended.
- the string builder
- Definition Classes
- TraversableOnce
(defined at scala.collection.TraversableOnce)
def addString(b: StringBuilder, start: String, sep: String, end: String): StringBuilder
Appends all elements of this traversable or iterator to a string builder using
start, end, and separator strings. The written text begins with the string
start
and ends with the string end
. Inside, the string representations
(w.r.t. the method toString
) of all elements of this traversable or iterator
are separated by the string sep
.
Example:
scala> val a = List(1,2,3,4)
a: List[Int] = List(1, 2, 3, 4)
scala> val b = new StringBuilder()
b: StringBuilder =
scala> a.addString(b , "List(" , ", " , ")")
res5: StringBuilder = List(1, 2, 3, 4)
- b
- the string builder to which elements are appended.
- start
- the starting string.
- sep
- the separator string.
- end
- the ending string.
- returns
- the string builder
b
to which elements were appended.
- the string builder
- Definition Classes
- TraversableOnce
(defined at scala.collection.TraversableOnce)
def aggregate[B](z: ⇒ B)(seqop: (B, A) ⇒ B, combop: (B, B) ⇒ B): B
Aggregates the results of applying an operator to subsequent elements.
This is a more general form of fold
and reduce
. It is similar to
foldLeft
in that it doesn’t require the result to be a supertype of the
element type. In addition, it allows parallel collections to be processed in
chunks, and then combines the intermediate results.
aggregate
splits the traversable or iterator into partitions and processes
each partition by sequentially applying seqop
, starting with z
(like
foldLeft
). Those intermediate results are then combined by using combop
(like fold
). The implementation of this operation may operate on an arbitrary
number of collection partitions (even 1), so combop
may be invoked an
arbitrary number of times (even 0).
As an example, consider summing up the integer values of a list of chars. The
initial value for the sum is 0. First, seqop
transforms each input character
to an Int and adds it to the sum (of the partition). Then, combop
just needs
to sum up the intermediate results of the partitions:
List('a', 'b', 'c').aggregate(0)({ (sum, ch) => sum + ch.toInt }, { (p1, p2) => p1 + p2 })
- B
- the type of accumulated results
- z
- the initial value for the accumulated result of the partition - this will
typically be the neutral element for the
seqop
operator (e.g.Nil
for list concatenation or0
for summation) and may be evaluated more than once
- the initial value for the accumulated result of the partition - this will
typically be the neutral element for the
- seqop
- an operator used to accumulate results within a partition
- combop
- an associative operator used to combine results from different partitions
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def collectFirst[B](pf: PartialFunction[A, B]): Option[B]
Finds the first element of the traversable or iterator for which the given partial function is defined, and applies the partial function to it.
Note: may not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered.
- pf
- the partial function
- returns
- an option value containing pf applied to the first value for which it is
defined, or
None
if none exists.
- an option value containing pf applied to the first value for which it is
defined, or
- Definition Classes
- TraversableOnce
Example:
Seq("a", 1, 5L).collectFirst({ case x: Int => x*10 }) = Some(10)
(defined at scala.collection.TraversableOnce)
def copyToArray[B >: A](xs: Array[B]): Unit
[use case]
Copies the elements of this immutable hash set to an array. Fills the given
array xs
with values of this immutable hash set. Copying will stop once either
the end of the current immutable hash set is reached, or the end of the target
array is reached.
- xs
- the array to fill.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def copyToArray[B >: A](xs: Array[B], start: Int): Unit
[use case]
Copies the elements of this immutable hash set to an array. Fills the given
array xs
with values of this immutable hash set, beginning at index start
.
Copying will stop once either the end of the current immutable hash set is
reached, or the end of the target array is reached.
- xs
- the array to fill.
- start
- the starting index.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def copyToBuffer[B >: A](dest: Buffer[B]): Unit
Copies all elements of this traversable or iterator to a buffer.
Note: will not terminate for infinite-sized collections.
- dest
- The buffer to which elements are copied.
- Definition Classes
- TraversableOnce
(defined at scala.collection.TraversableOnce)
def count(p: (A) ⇒ Boolean): Int
Counts the number of elements in the traversable or iterator which satisfy a predicate.
- p
- the predicate used to test elements.
- returns
- the number of elements satisfying the predicate
p
.
- the number of elements satisfying the predicate
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def foldLeft[B](z: B)(op: (B, A) ⇒ B): B
Applies a binary operator to a start value and all elements of this traversable or iterator, going left to right.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.
- B
- the result type of the binary operator.
- z
- the start value.
- op
- the binary operator.
- returns
- the result of inserting
op
between consecutive elements of this traversable or iterator, going left to right with the start valuez
on the left:
- the result of inserting
op(...op(z, x_1), x_2, ..., x_n)
where `x1, ..., xn` are the elements of this traversable or iterator.
Returns `z` if this traversable or iterator is empty.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1
Folds the elements of this traversable or iterator using the specified associative binary operator.
The order in which operations are performed on elements is unspecified and may be nondeterministic.
Note: will not terminate for infinite-sized collections.
- A1
- a type parameter for the binary operator, a supertype of
A
.
- a type parameter for the binary operator, a supertype of
- z
- a neutral element for the fold operation; may be added to the result an
arbitrary number of times, and must not change the result (e.g.,
Nil
for list concatenation, 0 for addition, or 1 for multiplication).
- a neutral element for the fold operation; may be added to the result an
arbitrary number of times, and must not change the result (e.g.,
- op
- a binary operator that must be associative.
- returns
- the result of applying the fold operator
op
between all the elements andz
, orz
if this traversable or iterator is empty.
- the result of applying the fold operator
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def maxBy[B](f: (A) ⇒ B)(implicit cmp: Ordering[B]): A
[use case]
Finds the first element which yields the largest value measured by function f.
- B
- The result type of the function f.
- f
- The measuring function.
- returns
- the first element of this immutable hash set with the largest value measured by function f.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def minBy[B](f: (A) ⇒ B)(implicit cmp: Ordering[B]): A
[use case]
Finds the first element which yields the smallest value measured by function f.
- B
- The result type of the function f.
- f
- The measuring function.
- returns
- the first element of this immutable hash set with the smallest value measured by function f.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def mkString(sep: String): String
Displays all elements of this traversable or iterator in a string using a separator string.
- sep
- the separator string.
- returns
- a string representation of this traversable or iterator. In the resulting
string the string representations (w.r.t. the method
toString
) of all elements of this traversable or iterator are separated by the stringsep
.
- a string representation of this traversable or iterator. In the resulting
string the string representations (w.r.t. the method
- Definition Classes
- TraversableOnce → GenTraversableOnce
Example:
List(1, 2, 3).mkString("|") = "1|2|3"
(defined at scala.collection.TraversableOnce)
def mkString(start: String, sep: String, end: String): String
Displays all elements of this traversable or iterator in a string using start, end, and separator strings.
- start
- the starting string.
- sep
- the separator string.
- end
- the ending string.
- returns
- a string representation of this traversable or iterator. The resulting
string begins with the string
start
and ends with the stringend
. Inside, the string representations (w.r.t. the methodtoString
) of all elements of this traversable or iterator are separated by the stringsep
.
- a string representation of this traversable or iterator. The resulting
string begins with the string
- Definition Classes
- TraversableOnce → GenTraversableOnce
Example:
List(1, 2, 3).mkString("(", "; ", ")") = "(1; 2; 3)"
(defined at scala.collection.TraversableOnce)
def reduceLeftOption[B >: A](op: (B, A) ⇒ B): Option[B]
Optionally applies a binary operator to all elements of this traversable or iterator, going left to right.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.
- B
- the result type of the binary operator.
- op
- the binary operator.
- returns
- an option value containing the result of
reduceLeft(op)
if this traversable or iterator is nonempty,None
otherwise.
- an option value containing the result of
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def reduceLeft[B >: A](op: (B, A) ⇒ B): B
Applies a binary operator to all elements of this traversable or iterator, going left to right.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.
- B
- the result type of the binary operator.
- op
- the binary operator.
- returns
- the result of inserting
op
between consecutive elements of this traversable or iterator, going left to right:
- the result of inserting
op( op( ... op(x_1, x_2) ..., x_{n-1}), x_n)
where `x1, ..., xn` are the elements of this traversable or iterator.
- Definition Classes
- TraversableOnce
- Exceptions thrown
- UnsupportedOperationException if this traversable or iterator is empty.
(defined at scala.collection.TraversableOnce)
def reduceOption[A1 >: A](op: (A1, A1) ⇒ A1): Option[A1]
Reduces the elements of this traversable or iterator, if any, using the specified associative binary operator.
The order in which operations are performed on elements is unspecified and may be nondeterministic.
- A1
- A type parameter for the binary operator, a supertype of
A
.
- A type parameter for the binary operator, a supertype of
- op
- A binary operator that must be associative.
- returns
- An option value containing result of applying reduce operator
op
between all the elements if the collection is nonempty, andNone
otherwise.
- An option value containing result of applying reduce operator
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def reduceRightOption[B >: A](op: (A, B) ⇒ B): Option[B]
Optionally applies a binary operator to all elements of this traversable or iterator, going right to left.
Note: will not terminate for infinite-sized collections.
Note: might return different results for different runs, unless the underlying collection type is ordered or the operator is associative and commutative.
- B
- the result type of the binary operator.
- op
- the binary operator.
- returns
- an option value containing the result of
reduceRight(op)
if this traversable or iterator is nonempty,None
otherwise.
- an option value containing the result of
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def reduce[A1 >: A](op: (A1, A1) ⇒ A1): A1
Reduces the elements of this traversable or iterator using the specified associative binary operator.
The order in which operations are performed on elements is unspecified and may be nondeterministic.
- A1
- A type parameter for the binary operator, a supertype of
A
.
- A type parameter for the binary operator, a supertype of
- op
- A binary operator that must be associative.
- returns
- The result of applying reduce operator
op
between all the elements if the traversable or iterator is nonempty.
- The result of applying reduce operator
- Definition Classes
- TraversableOnce → GenTraversableOnce
- Exceptions thrown
- UnsupportedOperationException if this traversable or iterator is empty.
(defined at scala.collection.TraversableOnce)
def reversed: scala.List[A]
- Attributes
- protected[this]
- Definition Classes
- TraversableOnce
(defined at scala.collection.TraversableOnce)
def toIndexedSeq: IndexedSeq[A]
Converts this traversable or iterator to an indexed sequence.
Note: will not terminate for infinite-sized collections.
- returns
- an indexed sequence containing all elements of this traversable or iterator.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def toList: scala.List[A]
Converts this traversable or iterator to a list.
Note: will not terminate for infinite-sized collections.
- returns
- a list containing all elements of this traversable or iterator.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def toMap[T, U](implicit ev: <:<[A, (T, U)]): Map[T, U]
[use case]
Converts this immutable hash set to a map. This method is unavailable unless the elements are members of Tuple2, each ((T, U)) becoming a key-value pair in the map. Duplicate keys will be overwritten by later keys: if this is an unordered collection, which key is in the resulting map is undefined.
- returns
- a map of type
immutable.Map[T, U]
containing all key/value pairs of type(T, U)
of this immutable hash set.
- a map of type
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
def toVector: scala.Vector[A]
Converts this traversable or iterator to a Vector.
Note: will not terminate for infinite-sized collections.
- returns
- a vector containing all elements of this traversable or iterator.
- Definition Classes
- TraversableOnce → GenTraversableOnce
(defined at scala.collection.TraversableOnce)
Value Members From scala.collection.generic.GenericTraversableTemplate
def flatten[B](implicit asTraversable: (A) ⇒ GenTraversableOnce[B]): HashSet[B]
[use case]
Converts this immutable hash set of traversable collections into a immutable hash set formed by the elements of these traversable collections.
The resulting collection’s type will be guided by the static type of immutable hash set. For example:
val xs = List(
Set(1, 2, 3),
Set(1, 2, 3)
).flatten
// xs == List(1, 2, 3, 1, 2, 3)
val ys = Set(
List(1, 2, 3),
List(3, 2, 1)
).flatten
// ys == Set(1, 2, 3)
- B
- the type of the elements of each traversable collection.
- returns
- a new immutable hash set resulting from concatenating all element immutable hash sets.
- Definition Classes
- GenericTraversableTemplate
(defined at scala.collection.generic.GenericTraversableTemplate)
def genericBuilder[B]: Builder[B, HashSet[B]]
The generic builder that builds instances of Traversable at arbitrary element types.
- Definition Classes
- GenericTraversableTemplate
(defined at scala.collection.generic.GenericTraversableTemplate)
def transpose[B](implicit asTraversable: (A) ⇒ GenTraversableOnce[B]): HashSet[HashSet[B]]
Transposes this collection of traversable collections into a collection of collections.
The resulting collection’s type will be guided by the static type of collection. For example:
val xs = List(
Set(1, 2, 3),
Set(4, 5, 6)).transpose
// xs == List(
// List(1, 4),
// List(2, 5),
// List(3, 6))
val ys = Vector(
List(1, 2, 3),
List(4, 5, 6)).transpose
// ys == Vector(
// Vector(1, 4),
// Vector(2, 5),
// Vector(3, 6))
- B
- the type of the elements of each traversable collection.
- asTraversable
- an implicit conversion which asserts that the element type of this
collection is a
Traversable
.
- an implicit conversion which asserts that the element type of this
collection is a
- returns
- a two-dimensional collection of collections which has as n th row the n th column of this collection.
- Definition Classes
- GenericTraversableTemplate
- Annotations
- @migration
- Migration
- (Changed in version 2.9.0)
transpose
throws anIllegalArgumentException
if collections are not uniformly sized.
- (Changed in version 2.9.0)
- Exceptions thrown
- IllegalArgumentException if all collections in this collection are not of the same size.
(defined at scala.collection.generic.GenericTraversableTemplate)
def unzip3[A1, A2, A3](implicit asTriple: (A) ⇒ (A1, A2, A3)): (HashSet[A1], HashSet[A2], HashSet[A3])
Converts this collection of triples into three collections of the first, second, and third element of each triple.
val xs = Traversable(
(1, "one", '1'),
(2, "two", '2'),
(3, "three", '3')).unzip3
// xs == (Traversable(1, 2, 3),
// Traversable(one, two, three),
// Traversable(1, 2, 3))
- A1
- the type of the first member of the element triples
- A2
- the type of the second member of the element triples
- A3
- the type of the third member of the element triples
- asTriple
- an implicit conversion which asserts that the element type of this collection is a triple.
- returns
- a triple of collections, containing the first, second, respectively third member of each element triple of this collection.
- Definition Classes
- GenericTraversableTemplate
(defined at scala.collection.generic.GenericTraversableTemplate)
def unzip[A1, A2](implicit asPair: (A) ⇒ (A1, A2)): (HashSet[A1], HashSet[A2])
Converts this collection of pairs into two collections of the first and second half of each pair.
val xs = Traversable(
(1, "one"),
(2, "two"),
(3, "three")).unzip
// xs == (Traversable(1, 2, 3),
// Traversable(one, two, three))
- A1
- the type of the first half of the element pairs
- A2
- the type of the second half of the element pairs
- asPair
- an implicit conversion which asserts that the element type of this collection is a pair.
- returns
- a pair of collections, containing the first, respectively second half of each element pair of this collection.
- Definition Classes
- GenericTraversableTemplate
(defined at scala.collection.generic.GenericTraversableTemplate)
Value Members From scala.collection.generic.Subtractable
def -(elem1: A, elem2: A, elems: A*): HashSet[A]
Creates a new collection from this collection with some elements removed.
This method takes two or more elements to be removed. Another overloaded variant of this method handles the case where a single element is removed.
- elem1
- the first element to remove.
- elem2
- the second element to remove.
- elems
- the remaining elements to remove.
- returns
- a new collection that contains all elements of the current collection except one less occurrence of each of the given elements.
- Definition Classes
- Subtractable
(defined at scala.collection.generic.Subtractable)
def --(xs: GenTraversableOnce[A]): HashSet[A]
Creates a new collection from this collection by removing all elements of another collection.
- xs
- the collection containing the removed elements.
- returns
- a new collection that contains all elements of the current collection except
one less occurrence of each of the elements of
elems
.
- a new collection that contains all elements of the current collection except
one less occurrence of each of the elements of
- Definition Classes
- Subtractable
(defined at scala.collection.generic.Subtractable)
Instance Constructors From scala.collection.immutable.HashSet
new HashSet()
(defined at scala.collection.immutable.HashSet)
Value Members From scala.collection.immutable.HashSet
def +(e: A): HashSet[A]
Creates a new set with an additional element, unless the element is already present.
- returns
- a new set that contains all elements of this set and that also contains
elem
.
- a new set that contains all elements of this set and that also contains
- Definition Classes
- HashSet → SetLike → GenSetLike
(defined at scala.collection.immutable.HashSet)
def +(elem1: A, elem2: A, elems: A*): HashSet[A]
Creates a new immutable hash set with additional elements, omitting duplicates.
This method takes two or more elements to be added. Elements that already exist in the immutable hash set will not be added. Another overloaded variant of this method handles the case where a single element is added.
Example:
scala> val a = Set(1, 3) + 2 + 3
a: scala.collection.immutable.Set[Int] = Set(1, 3, 2)
- elem1
- the first element to add.
- elem2
- the second element to add.
- elems
- the remaining elements to add.
- returns
- a new immutable hash set with the given elements added, omitting duplicates.
- Definition Classes
- HashSet → SetLike
(defined at scala.collection.immutable.HashSet)
def -(e: A): HashSet[A]
Creates a new set with a given element removed from this set.
- returns
- a new set that contains all elements of this set but that does not contain
elem
.
- a new set that contains all elements of this set but that does not contain
- Definition Classes
- HashSet → SetLike → Subtractable → GenSetLike
(defined at scala.collection.immutable.HashSet)
def companion: GenericCompanion[HashSet]
The factory companion object that builds instances of class immutable.HashSet
.
(or its Iterable
superclass where class immutable.HashSet
is not a Seq
.)
- Definition Classes
- HashSet → Set → Iterable → Traversable → Set → GenSet → Iterable → GenIterable → Traversable → GenTraversable → GenericTraversableTemplate
(defined at scala.collection.immutable.HashSet)
def contains(e: A): Boolean
Tests if some element is contained in this set.
- returns
true
ifelem
is contained in this set,false
otherwise.
- Definition Classes
- HashSet → SetLike → GenSetLike
(defined at scala.collection.immutable.HashSet)
def diff(that: GenSet[A]): HashSet[A]
Computes the difference of this set and another set.
- that
- the set of elements to exclude.
- returns
- a set containing those elements of this set that are not also contained in
the given set
that
.
- a set containing those elements of this set that are not also contained in
the given set
- Definition Classes
- HashSet → SetLike → GenSetLike
(defined at scala.collection.immutable.HashSet)
def elemHashCode(key: A): Int
- Attributes
- protected
(defined at scala.collection.immutable.HashSet)
def empty: HashSet[A]
The empty set of the same type as this set
- returns
- an empty set of type
This
.
- an empty set of type
- Definition Classes
- HashSet → SetLike → GenericSetTemplate
(defined at scala.collection.immutable.HashSet)
def filter(p: (A) ⇒ Boolean): HashSet[A]
Selects all elements of this immutable hash set which satisfy a predicate.
- p
- the predicate used to test elements.
- returns
- a new immutable hash set consisting of all elements of this immutable hash
set that satisfy the given predicate
p
. The order of the elements is preserved.
- a new immutable hash set consisting of all elements of this immutable hash
set that satisfy the given predicate
- Definition Classes
- HashSet → TraversableLike → GenTraversableLike
(defined at scala.collection.immutable.HashSet)
def filter0(p: (A) ⇒ Boolean, negate: Boolean, level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A]
- Attributes
- protected
(defined at scala.collection.immutable.HashSet)
def filterNot(p: (A) ⇒ Boolean): HashSet[A]
Selects all elements of this immutable hash set which do not satisfy a predicate.
- p
- the predicate used to test elements.
- returns
- a new immutable hash set consisting of all elements of this immutable hash
set that do not satisfy the given predicate
p
. The order of the elements is preserved.
- a new immutable hash set consisting of all elements of this immutable hash
set that do not satisfy the given predicate
- Definition Classes
- HashSet → TraversableLike → GenTraversableLike
(defined at scala.collection.immutable.HashSet)
def foreach[U](f: (A) ⇒ U): Unit
[use case]
Applies a function f
to all elements of this immutable hash set.
Note: this method underlies the implementation of most other bulk operations. Subclasses should re-implement this method if a more efficient implementation exists.
- f
- the function that is applied for its side-effect to every element. The
result of function
f
is discarded.
- the function that is applied for its side-effect to every element. The
result of function
- Definition Classes
- HashSet → IterableLike → GenericTraversableTemplate → TraversableLike → GenTraversableLike → TraversableOnce → GenTraversableOnce → FilterMonadic
(defined at scala.collection.immutable.HashSet)
def get0(key: A, hash: Int, level: Int): Boolean
- Attributes
- protected
(defined at scala.collection.immutable.HashSet)
final def improve(hcode: Int): Int
- Attributes
- protected
(defined at scala.collection.immutable.HashSet)
def intersect(that: GenSet[A]): HashSet[A]
Computes the intersection between this set and another set.
- that
- the set to intersect with.
- returns
- a new set consisting of all elements that are both in this set and in the
given set
that
.
- a new set consisting of all elements that are both in this set and in the
given set
- Definition Classes
- HashSet → GenSetLike
(defined at scala.collection.immutable.HashSet)
def par: ParHashSet[A]
Returns a parallel implementation of this collection.
For most collection types, this method creates a new parallel collection by
copying all the elements. For these collection, par
takes linear time. Mutable
collections in this category do not produce a mutable parallel collection that
has the same underlying dataset, so changes in one collection will not be
reflected in the other one.
Specific collections (e.g. ParArray
or mutable.ParHashMap
) override this
default behaviour by creating a parallel collection which shares the same
underlying dataset. For these collections, par
takes constant or sublinear
time.
All parallel collections return a reference to themselves.
- returns
- a parallel implementation of this collection
- Definition Classes
- HashSet → CustomParallelizable → Parallelizable
(defined at scala.collection.immutable.HashSet)
def removed0(key: A, hash: Int, level: Int): HashSet[A]
- Attributes
- protected
(defined at scala.collection.immutable.HashSet)
def subsetOf(that: GenSet[A]): Boolean
Tests whether this set is a subset of another set.
- that
- the set to test.
- returns
true
if this set is a subset ofthat
, i.e. if every element of this set is also an element ofthat
.
- Definition Classes
- HashSet → GenSetLike
(defined at scala.collection.immutable.HashSet)
def subsetOf0(that: HashSet[A], level: Int): Boolean
A specialized implementation of subsetOf for when both this and that are HashSet[A] and we can take advantage of the tree structure of both operands and the precalculated hashcodes of the HashSet1 instances.
- that
- the other set
- level
- the level of this and that hashset The purpose of level is to keep track of how deep we are in the tree. We need this information for when we arrive at a leaf and have to call get0 on that The value of level is 0 for a top-level HashSet and grows in increments of 5
- returns
- true if all elements of this set are contained in that set
- Attributes
- protected
(defined at scala.collection.immutable.HashSet)
def toSet[B >: A]: Set[B]
Returns this immutable hash set as an immutable set, perhaps accepting a wider
range of elements. Since it already is an immutable set, it will only be rebuilt
if the underlying structure cannot be expanded to include arbitrary element
types. For instance, BitSet
and SortedSet
will be rebuilt, as they require
Int
and sortable elements respectively.
When in doubt, the set will be rebuilt. Rebuilt sets never need to be rebuilt again.
- returns
- a set containing all elements of this immutable hash set.
- Definition Classes
- HashSet → Set → TraversableOnce → GenTraversableOnce
(defined at scala.collection.immutable.HashSet)
def union(that: GenSet[A]): HashSet[A]
Computes the union between of set and another set.
- that
- the set to form the union with.
- returns
- a new set consisting of all elements that are in this set or in the given
set
that
.
- a new set consisting of all elements that are in this set or in the given
set
- Definition Classes
- HashSet → SetLike → GenSetLike
(defined at scala.collection.immutable.HashSet)
Value Members From scala.collection.immutable.Set
def seq: Set[A]
A version of this collection with all of the operations implemented sequentially (i.e., in a single-threaded manner).
This method returns a reference to this collection. In parallel collections, it is redefined to return a sequential implementation of this collection. In both cases, it has O(1) complexity.
- returns
- a sequential view of the collection.
- Definition Classes
- Set → Set → GenSet → GenSetLike → Iterable → Iterable → GenIterable → Traversable → Traversable → GenTraversable → Parallelizable → TraversableOnce → GenTraversableOnce
(defined at scala.collection.immutable.Set)
Value Members From Implicit scala.collection.parallel.CollectionsHaveToParArray ——————————————————————————–
def toParArray: ParArray[T]
- Implicit information
- This member is added by an implicit conversion from HashSet [A] to CollectionsHaveToParArray [HashSet [A], T] performed by method CollectionsHaveToParArray in scala.collection.parallel. This conversion will take place only if an implicit value of type (HashSet [A]) ⇒ GenTraversableOnce [T] is in scope.
- Definition Classes
- CollectionsHaveToParArray (added by implicit convertion: scala.collection.parallel.CollectionsHaveToParArray)
Full Source:
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package scala
package collection
package immutable
import generic._
import scala.collection.parallel.immutable.ParHashSet
import scala.collection.GenSet
import scala.annotation.tailrec
/** This class implements immutable sets using a hash trie.
*
* '''Note:''' The builder of this hash set may return specialized representations for small sets.
*
* @tparam A the type of the elements contained in this hash set.
*
* @author Martin Odersky
* @author Tiark Rompf
* @version 2.8
* @since 2.3
* @define Coll `immutable.HashSet`
* @define coll immutable hash set
*/
@SerialVersionUID(2L)
@deprecatedInheritance("The implementation details of immutable hash sets make inheriting from them unwise.", "2.11.0")
class HashSet[A] extends AbstractSet[A]
with Set[A]
with GenericSetTemplate[A, HashSet]
with SetLike[A, HashSet[A]]
with CustomParallelizable[A, ParHashSet[A]]
with Serializable
{
import HashSet.{nullToEmpty, bufferSize, LeafHashSet}
override def companion: GenericCompanion[HashSet] = HashSet
//class HashSet[A] extends Set[A] with SetLike[A, HashSet[A]] {
override def par = ParHashSet.fromTrie(this)
override def size: Int = 0
override def empty = HashSet.empty[A]
def iterator: Iterator[A] = Iterator.empty
override def foreach[U](f: A => U): Unit = ()
def contains(e: A): Boolean = get0(e, computeHash(e), 0)
override def subsetOf(that: GenSet[A]) = that match {
case that:HashSet[A] =>
// call the specialized implementation with a level of 0 since both this and that are top-level hash sets
subsetOf0(that, 0)
case _ =>
// call the generic implementation
super.subsetOf(that)
}
/**
* A specialized implementation of subsetOf for when both this and that are HashSet[A] and we can take advantage
* of the tree structure of both operands and the precalculated hashcodes of the HashSet1 instances.
* @param that the other set
* @param level the level of this and that hashset
* The purpose of level is to keep track of how deep we are in the tree.
* We need this information for when we arrive at a leaf and have to call get0 on that
* The value of level is 0 for a top-level HashSet and grows in increments of 5
* @return true if all elements of this set are contained in that set
*/
protected def subsetOf0(that: HashSet[A], level: Int) = {
// The default implementation is for the empty set and returns true because the empty set is a subset of all sets
true
}
override def + (e: A): HashSet[A] = updated0(e, computeHash(e), 0)
override def + (elem1: A, elem2: A, elems: A*): HashSet[A] =
this + elem1 + elem2 ++ elems
override def union(that: GenSet[A]): HashSet[A] = that match {
case that: HashSet[A] =>
val buffer = new Array[HashSet[A]](bufferSize(this.size + that.size))
nullToEmpty(union0(that, 0, buffer, 0))
case _ => super.union(that)
}
override def intersect(that: GenSet[A]): HashSet[A] = that match {
case that: HashSet[A] =>
val buffer = new Array[HashSet[A]](bufferSize(this.size min that.size))
nullToEmpty(intersect0(that, 0, buffer, 0))
case _ => super.intersect(that)
}
override def diff(that: GenSet[A]): HashSet[A] = that match {
case that: HashSet[A] =>
val buffer = new Array[HashSet[A]](bufferSize(this.size))
nullToEmpty(diff0(that, 0, buffer, 0))
case _ => super.diff(that)
}
/**
* Union with a leaf HashSet at a given level.
* @param that a leaf HashSet
* @param level the depth in the tree. We need this when we have to create a branch node on top of this and that
* @return The union of this and that at the given level. Unless level is zero, the result is not a self-contained
* HashSet but needs to be stored at the correct depth
*/
private[immutable] def union0(that: LeafHashSet[A], level: Int): HashSet[A] = {
// the default implementation is for the empty set, so we just return that
that
}
/**
* Union with a HashSet at a given level
* @param that a HashSet
* @param level the depth in the tree. We need to keep track of the level to know how deep we are in the tree
* @param buffer a temporary buffer that is used for temporarily storing elements when creating new branch nodes
* @param offset0 the first offset into the buffer in which we are allowed to write
* @return The union of this and that at the given level. Unless level is zero, the result is not a self-contained
* HashSet but needs to be stored at the correct depth
*/
private[immutable] def union0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = {
// the default implementation is for the empty set, so we just return that
that
}
/**
* Intersection with another hash set at a given level
* @param level the depth in the tree. We need to keep track of the level to know how deep we are in the tree
* @param buffer a temporary buffer that is used for temporarily storing elements when creating new branch nodes
* @param offset0 the first offset into the buffer in which we are allowed to write
* @return The intersection of this and that at the given level. Unless level is zero, the result is not a
* self-contained HashSet but needs to be stored at the correct depth
*/
private[immutable] def intersect0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = {
// the default implementation is for the empty set, so we just return the empty set
null
}
/**
* Diff with another hash set at a given level
* @param level the depth in the tree. We need to keep track of the level to know how deep we are in the tree
* @param buffer a temporary buffer that is used for temporarily storing elements when creating new branch nodes
* @param offset0 the first offset into the buffer in which we are allowed to write
* @return The diff of this and that at the given level. Unless level is zero, the result is not a
* self-contained HashSet but needs to be stored at the correct depth
*/
private[immutable] def diff0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = {
// the default implementation is for the empty set, so we just return the empty set
null
}
def - (e: A): HashSet[A] =
nullToEmpty(removed0(e, computeHash(e), 0))
override def filter(p: A => Boolean) = {
val buffer = new Array[HashSet[A]](bufferSize(size))
nullToEmpty(filter0(p, false, 0, buffer, 0))
}
override def filterNot(p: A => Boolean) = {
val buffer = new Array[HashSet[A]](bufferSize(size))
nullToEmpty(filter0(p, true, 0, buffer, 0))
}
protected def filter0(p: A => Boolean, negate: Boolean, level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = null
protected def elemHashCode(key: A) = key.##
protected final def improve(hcode: Int) = {
var h: Int = hcode + ~(hcode << 9)
h = h ^ (h >>> 14)
h = h + (h << 4)
h ^ (h >>> 10)
}
private[collection] def computeHash(key: A) = improve(elemHashCode(key))
protected def get0(key: A, hash: Int, level: Int): Boolean = false
private[collection] def updated0(key: A, hash: Int, level: Int): HashSet[A] =
new HashSet.HashSet1(key, hash)
protected def removed0(key: A, hash: Int, level: Int): HashSet[A] = this
protected def writeReplace(): AnyRef = new HashSet.SerializationProxy(this)
override def toSet[B >: A]: Set[B] = this.asInstanceOf[HashSet[B]]
}
/** $factoryInfo
* @define Coll `immutable.HashSet`
* @define coll immutable hash set
*
* @author Tiark Rompf
* @since 2.3
* @define Coll `immutable.HashSet`
* @define coll immutable hash set
* @define mayNotTerminateInf
* @define willNotTerminateInf
*/
object HashSet extends ImmutableSetFactory[HashSet] {
/** $setCanBuildFromInfo */
implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, HashSet[A]] = setCanBuildFrom[A]
private object EmptyHashSet extends HashSet[Any] { }
private[collection] def emptyInstance: HashSet[Any] = EmptyHashSet
// utility method to create a HashTrieSet from two leaf HashSets (HashSet1 or HashSetCollision1) with non-colliding hash code)
private def makeHashTrieSet[A](hash0:Int, elem0:HashSet[A], hash1:Int, elem1:HashSet[A], level:Int) : HashTrieSet[A] = {
val index0 = (hash0 >>> level) & 0x1f
val index1 = (hash1 >>> level) & 0x1f
if(index0 != index1) {
val bitmap = (1 << index0) | (1 << index1)
val elems = new Array[HashSet[A]](2)
if(index0 < index1) {
elems(0) = elem0
elems(1) = elem1
} else {
elems(0) = elem1
elems(1) = elem0
}
new HashTrieSet[A](bitmap, elems, elem0.size + elem1.size)
} else {
val elems = new Array[HashSet[A]](1)
val bitmap = (1 << index0)
val child = makeHashTrieSet(hash0, elem0, hash1, elem1, level + 5)
elems(0) = child
new HashTrieSet[A](bitmap, elems, child.size)
}
}
/**
* Common superclass of HashSet1 and HashSetCollision1, which are the two possible leaves of the Trie
*/
private[HashSet] sealed abstract class LeafHashSet[A] extends HashSet[A] {
private[HashSet] def hash:Int
}
class HashSet1[A](private[HashSet] val key: A, private[HashSet] val hash: Int) extends LeafHashSet[A] {
override def size = 1
override protected def get0(key: A, hash: Int, level: Int): Boolean =
(hash == this.hash && key == this.key)
override protected def subsetOf0(that: HashSet[A], level: Int) = {
// check if that contains this.key
// we use get0 with our key and hash at the correct level instead of calling contains,
// which would not work since that might not be a top-level HashSet
// and in any case would be inefficient because it would require recalculating the hash code
that.get0(key, hash, level)
}
override private[collection] def updated0(key: A, hash: Int, level: Int): HashSet[A] =
if (hash == this.hash && key == this.key) this
else {
if (hash != this.hash) {
makeHashTrieSet(this.hash, this, hash, new HashSet1(key, hash), level)
} else {
// 32-bit hash collision (rare, but not impossible)
new HashSetCollision1(hash, ListSet.empty + this.key + key)
}
}
override private[immutable] def union0(that: LeafHashSet[A], level: Int): HashSet[A] = that match {
case that if that.hash != this.hash =>
// different hash code, so there is no need to investigate further.
// Just create a branch node containing the two.
makeHashTrieSet(this.hash, this, that.hash, that, level)
case that: HashSet1[A] =>
if (this.key == that.key) {
this
} else {
// 32-bit hash collision (rare, but not impossible)
new HashSetCollision1[A](hash, ListSet.empty + this.key + that.key)
}
case that: HashSetCollision1[A] =>
val ks1 = that.ks + key
// Could use eq check (faster) if ListSet was guaranteed to return itself
if (ks1.size == that.ks.size) {
that
} else {
new HashSetCollision1[A](hash, ks1)
}
}
override private[immutable] def union0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int) = {
// switch to the Leaf version of union
// we can exchange the arguments because union is symmetrical
that.union0(this, level)
}
override private[immutable] def intersect0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] =
if (that.get0(key, hash, level)) this else null
override private[immutable] def diff0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] =
if (that.get0(key, hash, level)) null else this
override protected def removed0(key: A, hash: Int, level: Int): HashSet[A] =
if (hash == this.hash && key == this.key) null else this
override protected def filter0(p: A => Boolean, negate: Boolean, level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] =
if (negate ^ p(key)) this else null
override def iterator: Iterator[A] = Iterator(key)
override def foreach[U](f: A => U): Unit = f(key)
}
private[immutable] class HashSetCollision1[A](private[HashSet] val hash: Int, val ks: ListSet[A]) extends LeafHashSet[A] {
override def size = ks.size
override protected def get0(key: A, hash: Int, level: Int): Boolean =
if (hash == this.hash) ks.contains(key) else false
override protected def subsetOf0(that: HashSet[A], level: Int) = {
// we have to check each element
// we use get0 with our hash at the correct level instead of calling contains,
// which would not work since that might not be a top-level HashSet
// and in any case would be inefficient because it would require recalculating the hash code
ks.forall(key => that.get0(key, hash, level))
}
override private[collection] def updated0(key: A, hash: Int, level: Int): HashSet[A] =
if (hash == this.hash) new HashSetCollision1(hash, ks + key)
else makeHashTrieSet(this.hash, this, hash, new HashSet1(key, hash), level)
override private[immutable] def union0(that: LeafHashSet[A], level: Int): HashSet[A] = that match {
case that if that.hash != this.hash =>
// different hash code, so there is no need to investigate further.
// Just create a branch node containing the two.
makeHashTrieSet(this.hash, this, that.hash, that, level)
case that: HashSet1[A] =>
val ks1 = ks + that.key
// Could use eq check (faster) if ListSet was guaranteed to return itself
if (ks1.size == ks.size) {
this
} else {
// create a new HashSetCollision with the existing hash
// we don't have to check for size=1 because union is never going to remove elements
new HashSetCollision1[A](hash, ks1)
}
case that: HashSetCollision1[A] =>
val ks1 = this.ks ++ that.ks
ks1.size match {
case size if size == this.ks.size =>
// could this check be made faster by doing an eq check?
// I am not sure we can rely on ListSet returning itself when all elements are already in the set,
// so it seems unwise to rely on it.
this
case size if size == that.ks.size =>
// we have to check this as well, since we don't want to create a new instance if this is a subset of that
that
case _ =>
// create a new HashSetCollision with the existing hash
// we don't have to check for size=1 because union is never going to remove elements
new HashSetCollision1[A](hash, ks1)
}
}
override private[immutable] def union0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = that match {
case that: LeafHashSet[A] =>
// switch to the simpler Tree/Leaf implementation
this.union0(that, level)
case that: HashTrieSet[A] =>
// switch to the simpler Tree/Leaf implementation
// we can swap this and that because union is symmetrical
that.union0(this, level)
case _ => this
}
override private[immutable] def intersect0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = {
// filter the keys, taking advantage of the fact that we know their hash code
val ks1 = ks.filter(that.get0(_, hash, level))
ks1.size match {
case 0 =>
// the empty set
null
case size if size == this.size =>
// unchanged
// We do this check first since even if the result is of size 1 since
// it is preferable to return the existing set for better structural sharing
this
case size if size == that.size =>
// the other set
// We do this check first since even if the result is of size 1 since
// it is preferable to return the existing set for better structural sharing
that
case 1 =>
// create a new HashSet1 with the hash we already know
new HashSet1(ks1.head, hash)
case _ =>
// create a new HashSetCollision with the hash we already know and the new keys
new HashSetCollision1(hash, ks1)
}
}
override private[immutable] def diff0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = {
val ks1 = ks.filterNot(that.get0(_, hash, level))
ks1.size match {
case 0 =>
// the empty set
null
case size if size == this.size =>
// unchanged
// We do this check first since even if the result is of size 1 since
// it is preferable to return the existing set for better structural sharing
this
case 1 =>
// create a new HashSet1 with the hash we already know
new HashSet1(ks1.head, hash)
case _ =>
// create a new HashSetCollision with the hash we already know and the new keys
new HashSetCollision1(hash, ks1)
}
}
override protected def removed0(key: A, hash: Int, level: Int): HashSet[A] =
if (hash == this.hash) {
val ks1 = ks - key
ks1.size match {
case 0 =>
// the empty set
null
case 1 =>
// create a new HashSet1 with the hash we already know
new HashSet1(ks1.head, hash)
case size if size == ks.size =>
// Should only have HSC1 if size > 1
this
case _ =>
// create a new HashSetCollision with the hash we already know and the new keys
new HashSetCollision1(hash, ks1)
}
} else this
override protected def filter0(p: A => Boolean, negate: Boolean, level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = {
val ks1 = if(negate) ks.filterNot(p) else ks.filter(p)
ks1.size match {
case 0 =>
null
case 1 =>
new HashSet1(ks1.head, hash)
case x if x == ks.size =>
this
case _ =>
new HashSetCollision1(hash, ks1)
}
}
override def iterator: Iterator[A] = ks.iterator
override def foreach[U](f: A => U): Unit = ks.foreach(f)
private def writeObject(out: java.io.ObjectOutputStream) {
// this cannot work - reading things in might produce different
// hash codes and remove the collision. however this is never called
// because no references to this class are ever handed out to client code
// and HashTrieSet serialization takes care of the situation
sys.error("cannot serialize an immutable.HashSet where all items have the same 32-bit hash code")
//out.writeObject(kvs)
}
private def readObject(in: java.io.ObjectInputStream) {
sys.error("cannot deserialize an immutable.HashSet where all items have the same 32-bit hash code")
//kvs = in.readObject().asInstanceOf[ListSet[A]]
//hash = computeHash(kvs.)
}
}
/**
* A branch node of the HashTrieSet with at least one and up to 32 children.
*
* @param bitmap encodes which element corresponds to which child
* @param elems the up to 32 children of this node.
* the number of children must be identical to the number of 1 bits in bitmap
* @param size0 the total number of elements. This is stored just for performance reasons.
* @tparam A the type of the elements contained in this hash set.
*
* How levels work:
*
* When looking up or adding elements, the part of the hashcode that is used to address the children array depends
* on how deep we are in the tree. This is accomplished by having a level parameter in all internal methods
* that starts at 0 and increases by 5 (32 = 2^5) every time we go deeper into the tree.
*
* hashcode (binary): 00000000000000000000000000000000
* level=0 (depth=0) ^^^^^
* level=5 (depth=1) ^^^^^
* level=10 (depth=2) ^^^^^
* ...
*
* Be careful: a non-toplevel HashTrieSet is not a self-contained set, so e.g. calling contains on it will not work!
* It relies on its depth in the Trie for which part of a hash to use to address the children, but this information
* (the level) is not stored due to storage efficiency reasons but has to be passed explicitly!
*
* How bitmap and elems correspond:
*
* A naive implementation of a HashTrieSet would always have an array of size 32 for children and leave the unused
* children empty (null). But that would be very wasteful regarding memory. Instead, only non-empty children are
* stored in elems, and the bitmap is used to encode which elem corresponds to which child bucket. The lowest 1 bit
* corresponds to the first element, the second-lowest to the second, etc.
*
* bitmap (binary): 00010000000000000000100000000000
* elems: [a,b]
* children: ---b----------------a-----------
*/
class HashTrieSet[A](private val bitmap: Int, private[collection] val elems: Array[HashSet[A]], private val size0: Int)
extends HashSet[A] {
assert(Integer.bitCount(bitmap) == elems.length)
// assertion has to remain disabled until SI-6197 is solved
// assert(elems.length > 1 || (elems.length == 1 && elems(0).isInstanceOf[HashTrieSet[_]]))
override def size = size0
override protected def get0(key: A, hash: Int, level: Int): Boolean = {
val index = (hash >>> level) & 0x1f
val mask = (1 << index)
if (bitmap == - 1) {
elems(index & 0x1f).get0(key, hash, level + 5)
} else if ((bitmap & mask) != 0) {
val offset = Integer.bitCount(bitmap & (mask-1))
elems(offset).get0(key, hash, level + 5)
} else
false
}
override private[collection] def updated0(key: A, hash: Int, level: Int): HashSet[A] = {
val index = (hash >>> level) & 0x1f
val mask = (1 << index)
val offset = Integer.bitCount(bitmap & (mask-1))
if ((bitmap & mask) != 0) {
val sub = elems(offset)
val subNew = sub.updated0(key, hash, level + 5)
if (sub eq subNew) this
else {
val elemsNew = new Array[HashSet[A]](elems.length)
Array.copy(elems, 0, elemsNew, 0, elems.length)
elemsNew(offset) = subNew
new HashTrieSet(bitmap, elemsNew, size + (subNew.size - sub.size))
}
} else {
val elemsNew = new Array[HashSet[A]](elems.length + 1)
Array.copy(elems, 0, elemsNew, 0, offset)
elemsNew(offset) = new HashSet1(key, hash)
Array.copy(elems, offset, elemsNew, offset + 1, elems.length - offset)
val bitmapNew = bitmap | mask
new HashTrieSet(bitmapNew, elemsNew, size + 1)
}
}
override private[immutable] def union0(that: LeafHashSet[A], level: Int): HashSet[A] = {
val index = (that.hash >>> level) & 0x1f
val mask = (1 << index)
val offset = Integer.bitCount(bitmap & (mask - 1))
if ((bitmap & mask) != 0) {
val sub = elems(offset)
val sub1 = sub.union0(that, level + 5)
if (sub eq sub1) this
else {
val elems1 = new Array[HashSet[A]](elems.length)
Array.copy(elems, 0, elems1, 0, elems.length)
elems1(offset) = sub1
new HashTrieSet(bitmap, elems1, size + (sub1.size - sub.size))
}
} else {
val elems1 = new Array[HashSet[A]](elems.length + 1)
Array.copy(elems, 0, elems1, 0, offset)
elems1(offset) = that
Array.copy(elems, offset, elems1, offset + 1, elems.length - offset)
val bitmap1 = bitmap | mask
new HashTrieSet(bitmap1, elems1, size + that.size)
}
}
override private[immutable] def union0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = that match {
case that if that eq this =>
// shortcut for when that is this
// this happens often for nodes deeper in the tree, especially when that and this share a common "heritage"
// e.g. you have a large set A and do some small operations (adding and removing elements) to it to create B
// then A and B will have the vast majority of nodes in common, and this eq check will allow not even looking
// at these nodes.
this
case that: LeafHashSet[A] =>
// when that is a leaf, we can switch to the simpler Tree/Leaf implementation
this.union0(that, level)
case that: HashTrieSet[A] =>
val a = this.elems
var abm = this.bitmap
var ai = 0
val b = that.elems
var bbm = that.bitmap
var bi = 0
// fetch a new temporary array that is guaranteed to be big enough (32 elements)
var offset = offset0
var rs = 0
// loop as long as there are bits left in either abm or bbm
while ((abm | bbm) != 0) {
// lowest remaining bit in abm
val alsb = abm ^ (abm & (abm - 1))
// lowest remaining bit in bbm
val blsb = bbm ^ (bbm & (bbm - 1))
if (alsb == blsb) {
val sub1 = a(ai).union0(b(bi), level + 5, buffer, offset)
rs += sub1.size
buffer(offset) = sub1
offset += 1
// clear lowest remaining one bit in abm and increase the a index
abm &= ~alsb
ai += 1
// clear lowest remaining one bit in bbm and increase the b index
bbm &= ~blsb
bi += 1
} else if (unsignedCompare(alsb - 1, blsb - 1)) {
// alsb is smaller than blsb, or alsb is set and blsb is 0
// in any case, alsb is guaranteed to be set here!
val sub1 = a(ai)
rs += sub1.size
buffer(offset) = sub1
offset += 1
// clear lowest remaining one bit in abm and increase the a index
abm &= ~alsb
ai += 1
} else {
// blsb is smaller than alsb, or blsb is set and alsb is 0
// in any case, blsb is guaranteed to be set here!
val sub1 = b(bi)
rs += sub1.size
buffer(offset) = sub1
offset += 1
// clear lowest remaining one bit in bbm and increase the b index
bbm &= ~blsb
bi += 1
}
}
if (rs == this.size) {
// if the result would be identical to this, we might as well return this
this
} else if (rs == that.size) {
// if the result would be identical to that, we might as well return that
that
} else {
// we don't have to check whether the result is a leaf, since union will only make the set larger
// and this is not a leaf to begin with.
val length = offset - offset0
val elems = new Array[HashSet[A]](length)
System.arraycopy(buffer, offset0, elems, 0, length)
new HashTrieSet(this.bitmap | that.bitmap, elems, rs)
}
case _ => this
}
override private[immutable] def intersect0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = that match {
case that if that eq this =>
// shortcut for when that is this
// this happens often for nodes deeper in the tree, especially when that and this share a common "heritage"
// e.g. you have a large set A and do some small operations (adding and removing elements) to it to create B
// then A and B will have the vast majority of nodes in common, and this eq check will allow not even looking
// at these nodes!
this
case that: LeafHashSet[A] =>
// when that is a leaf, we can switch to the simpler Tree/Leaf implementation
// it is OK to swap the arguments because intersect is symmetric
// (we can't do this in case of diff, which is not symmetric)
that.intersect0(this, level, buffer, offset0)
case that: HashTrieSet[A] =>
val a = this.elems
var abm = this.bitmap
var ai = 0
val b = that.elems
var bbm = that.bitmap
var bi = 0
// if the bitmasks do not overlap, the result is definitely empty so we can abort here
if ((abm & bbm) == 0)
return null
// fetch a new temporary array that is guaranteed to be big enough (32 elements)
var offset = offset0
var rs = 0
var rbm = 0
// loop as long as there are bits left that are set in both abm and bbm
while ((abm & bbm) != 0) {
// highest remaining bit in abm
val alsb = abm ^ (abm & (abm - 1))
// highest remaining bit in bbm
val blsb = bbm ^ (bbm & (bbm - 1))
if (alsb == blsb) {
val sub1 = a(ai).intersect0(b(bi), level + 5, buffer, offset)
if (sub1 ne null) {
rs += sub1.size
rbm |= alsb
buffer(offset) = sub1
offset += 1
}
// clear lowest remaining one bit in abm and increase the a index
abm &= ~alsb;
ai += 1
// clear lowest remaining one bit in bbm and increase the b index
bbm &= ~blsb;
bi += 1
} else if (unsignedCompare(alsb - 1, blsb - 1)) {
// alsb is smaller than blsb, or alsb is set and blsb is 0
// in any case, alsb is guaranteed to be set here!
// clear lowest remaining one bit in abm and increase the a index
abm &= ~alsb;
ai += 1
} else {
// blsb is smaller than alsb, or blsb is set and alsb is 0
// in any case, blsb is guaranteed to be set here!
// clear lowest remaining one bit in bbm and increase the b index
bbm &= ~blsb;
bi += 1
}
}
if (rbm == 0) {
// if the result bitmap is empty, the result is the empty set
null
} else if (rs == size0) {
// if the result has the same number of elements as this, it must be identical to this,
// so we might as well return this
this
} else if (rs == that.size0) {
// if the result has the same number of elements as that, it must be identical to that,
// so we might as well return that
that
} else {
val length = offset - offset0
if (length == 1 && !buffer(offset0).isInstanceOf[HashTrieSet[A]])
buffer(offset0)
else {
val elems = new Array[HashSet[A]](length)
System.arraycopy(buffer, offset0, elems, 0, length)
new HashTrieSet[A](rbm, elems, rs)
}
}
case _ => null
}
override private[immutable] def diff0(that: HashSet[A], level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = that match {
case that if that eq this =>
// shortcut for when that is this
// this happens often for nodes deeper in the tree, especially when that and this share a common "heritage"
// e.g. you have a large set A and do some small operations (adding and removing elements) to it to create B
// then A and B will have the vast majority of nodes in common, and this eq check will allow not even looking
// at these nodes!
null
case that: HashSet1[A] =>
removed0(that.key, that.hash, level)
case that: HashTrieSet[A] =>
val a = this.elems
var abm = this.bitmap
var ai = 0
val b = that.elems
var bbm = that.bitmap
var bi = 0
// fetch a new temporary array that is guaranteed to be big enough (32 elements)
var offset = offset0
var rs = 0
var rbm = 0
// loop until there are no more bits in abm
while(abm!=0) {
// highest remaining bit in abm
val alsb = abm ^ (abm & (abm - 1))
// highest remaining bit in bbm
val blsb = bbm ^ (bbm & (bbm - 1))
if (alsb == blsb) {
val sub1 = a(ai).diff0(b(bi), level + 5, buffer, offset)
if (sub1 ne null) {
rs += sub1.size
rbm |= alsb
buffer(offset) = sub1
offset += 1
}
// clear lowest remaining one bit in abm and increase the a index
abm &= ~alsb; ai += 1
// clear lowest remaining one bit in bbm and increase the b index
bbm &= ~blsb; bi += 1
} else if (unsignedCompare(alsb - 1, blsb - 1)) {
// alsb is smaller than blsb, or alsb is set and blsb is 0
// in any case, alsb is guaranteed to be set here!
val sub1 = a(ai)
rs += sub1.size
rbm |= alsb
buffer(offset) = sub1; offset += 1
// clear lowest remaining one bit in abm and increase the a index
abm &= ~alsb; ai += 1
} else {
// blsb is smaller than alsb, or blsb is set and alsb is 0
// in any case, blsb is guaranteed to be set here!
// clear lowest remaining one bit in bbm and increase the b index
bbm &= ~blsb; bi += 1
}
}
if (rbm == 0) {
null
} else if (rs == this.size0) {
// if the result has the same number of elements as this, it must be identical to this,
// so we might as well return this
this
} else {
val length = offset - offset0
if (length == 1 && !buffer(offset0).isInstanceOf[HashTrieSet[A]])
buffer(offset0)
else {
val elems = new Array[HashSet[A]](length)
System.arraycopy(buffer, offset0, elems, 0, length)
new HashTrieSet[A](rbm, elems, rs)
}
}
case that: HashSetCollision1[A] =>
// we remove the elements using removed0 so we can use the fact that we know the hash of all elements
// to be removed
@tailrec def removeAll(s:HashSet[A], r:ListSet[A]) : HashSet[A] =
if(r.isEmpty || (s eq null)) s
else removeAll(s.removed0(r.head, that.hash, level), r.tail)
removeAll(this, that.ks)
case _ => this
}
override protected def removed0(key: A, hash: Int, level: Int): HashSet[A] = {
val index = (hash >>> level) & 0x1f
val mask = (1 << index)
val offset = Integer.bitCount(bitmap & (mask-1))
if ((bitmap & mask) != 0) {
val sub = elems(offset)
val subNew = sub.removed0(key, hash, level + 5)
if (sub eq subNew) this
else if (subNew eq null) {
val bitmapNew = bitmap ^ mask
if (bitmapNew != 0) {
val elemsNew = new Array[HashSet[A]](elems.length - 1)
Array.copy(elems, 0, elemsNew, 0, offset)
Array.copy(elems, offset + 1, elemsNew, offset, elems.length - offset - 1)
val sizeNew = size - sub.size
// if we have only one child, which is not a HashTrieSet but a self-contained set like
// HashSet1 or HashSetCollision1, return the child instead
if (elemsNew.length == 1 && !elemsNew(0).isInstanceOf[HashTrieSet[_]])
elemsNew(0)
else
new HashTrieSet(bitmapNew, elemsNew, sizeNew)
} else
null
} else if(elems.length == 1 && !subNew.isInstanceOf[HashTrieSet[_]]) {
subNew
} else {
val elemsNew = new Array[HashSet[A]](elems.length)
Array.copy(elems, 0, elemsNew, 0, elems.length)
elemsNew(offset) = subNew
val sizeNew = size + (subNew.size - sub.size)
new HashTrieSet(bitmap, elemsNew, sizeNew)
}
} else {
this
}
}
override protected def subsetOf0(that: HashSet[A], level: Int): Boolean = if (that eq this) true else that match {
case that: HashTrieSet[A] if this.size0 <= that.size0 =>
// create local mutable copies of members
var abm = this.bitmap
val a = this.elems
var ai = 0
val b = that.elems
var bbm = that.bitmap
var bi = 0
if ((abm & bbm) == abm) {
// I tried rewriting this using tail recursion, but the generated java byte code was less than optimal
while(abm!=0) {
// highest remaining bit in abm
val alsb = abm ^ (abm & (abm - 1))
// highest remaining bit in bbm
val blsb = bbm ^ (bbm & (bbm - 1))
// if both trees have a bit set at the same position, we need to check the subtrees
if (alsb == blsb) {
// we are doing a comparison of a child of this with a child of that,
// so we have to increase the level by 5 to keep track of how deep we are in the tree
if (!a(ai).subsetOf0(b(bi), level + 5))
return false
// clear lowest remaining one bit in abm and increase the a index
abm &= ~alsb; ai += 1
}
// clear lowermost remaining one bit in bbm and increase the b index
// we must do this in any case
bbm &= ~blsb; bi += 1
}
true
} else {
// the bitmap of this contains more one bits than the bitmap of that,
// so this can not possibly be a subset of that
false
}
case _ =>
// if the other set is a HashTrieSet but has less elements than this, it can not be a subset
// if the other set is a HashSet1, we can not be a subset of it because we are a HashTrieSet with at least two children (see assertion)
// if the other set is a HashSetCollision1, we can not be a subset of it because we are a HashTrieSet with at least two different hash codes
// if the other set is the empty set, we are not a subset of it because we are not empty
false
}
override protected def filter0(p: A => Boolean, negate: Boolean, level: Int, buffer: Array[HashSet[A]], offset0: Int): HashSet[A] = {
// current offset
var offset = offset0
// result size
var rs = 0
// bitmap for kept elems
var kept = 0
// loop over all elements
var i = 0
while (i < elems.length) {
val result = elems(i).filter0(p, negate, level + 5, buffer, offset)
if (result ne null) {
buffer(offset) = result
offset += 1
// add the result size
rs += result.size
// mark the bit i as kept
kept |= (1 << i)
}
i += 1
}
if (offset == offset0) {
// empty
null
} else if (rs == size0) {
// unchanged
this
} else if (offset == offset0 + 1 && !buffer(offset0).isInstanceOf[HashTrieSet[A]]) {
// leaf
buffer(offset0)
} else {
// we have to return a HashTrieSet
val length = offset - offset0
val elems1 = new Array[HashSet[A]](length)
System.arraycopy(buffer, offset0, elems1, 0, length)
val bitmap1 = if (length == elems.length) {
// we can reuse the original bitmap
bitmap
} else {
// calculate new bitmap by keeping just bits in the kept bitmask
keepBits(bitmap, kept)
}
new HashTrieSet(bitmap1, elems1, rs)
}
}
override def iterator = new TrieIterator[A](elems.asInstanceOf[Array[Iterable[A]]]) {
final override def getElem(cc: AnyRef): A = cc.asInstanceOf[HashSet1[A]].key
}
override def foreach[U](f: A => U): Unit = {
var i = 0
while (i < elems.length) {
elems(i).foreach(f)
i += 1
}
}
}
/**
* Calculates the maximum buffer size given the maximum possible total size of the trie-based collection
* @param size the maximum size of the collection to be generated
* @return the maximum buffer size
*/
@inline private def bufferSize(size: Int): Int = (size + 6) min (32 * 7)
/**
* In many internal operations the empty set is represented as null for performance reasons. This method converts
* null to the empty set for use in public methods
*/
@inline private def nullToEmpty[A](s: HashSet[A]): HashSet[A] = if (s eq null) empty[A] else s
/**
* Utility method to keep a subset of all bits in a given bitmap
*
* Example
* bitmap (binary): 00000001000000010000000100000001
* keep (binary): 1010
* result (binary): 00000001000000000000000100000000
*
* @param bitmap the bitmap
* @param keep a bitmask containing which bits to keep
* @return the original bitmap with all bits where keep is not 1 set to 0
*/
private def keepBits(bitmap: Int, keep: Int): Int = {
var result = 0
var current = bitmap
var kept = keep
while (kept != 0) {
// lowest remaining bit in current
val lsb = current ^ (current & (current - 1))
if ((kept & 1) != 0) {
// mark bit in result bitmap
result |= lsb
}
// clear lowest remaining one bit in abm
current &= ~lsb
// look at the next kept bit
kept >>>= 1
}
result
}
// unsigned comparison
@inline private[this] def unsignedCompare(i: Int, j: Int) =
(i < j) ^ (i < 0) ^ (j < 0)
@SerialVersionUID(2L) private class SerializationProxy[A,B](@transient private var orig: HashSet[A]) extends Serializable {
private def writeObject(out: java.io.ObjectOutputStream) {
val s = orig.size
out.writeInt(s)
for (e <- orig) {
out.writeObject(e)
}
}
private def readObject(in: java.io.ObjectInputStream) {
orig = empty
val s = in.readInt()
for (i <- 0 until s) {
val e = in.readObject().asInstanceOf[A]
orig = orig + e
}
}
private def readResolve(): AnyRef = orig
}
}
Interested in Scala?
I send out weekly, personalized emails with articles and conference talks.
Subscribe now.