score:24
The documentation says If this is empty then it does nothing and returns that. Otherwise, appends that to this.
. That is exactly, what you observed. If you really need a mutable list, I would suggest you to use scala.collection.mutable.ListBuffer
instead, with it you can do
val lb = new ListBuffer[Int]
scala> lb += 1
res14: lb.type = ListBuffer(1)
scala> lb
res15: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1)
scala> lb ++= Seq(1,2,3)
res17: lb.type = ListBuffer(1, 1, 2, 3, 1, 2, 3)
scala> lb
res18: scala.collection.mutable.ListBuffer[Int] = ListBuffer(1, 1, 2, 3, 1, 2, 3)
score:3
As I understand it is related to First/Last (Nil
) element in the list (if list is empty Nil
is first and last element at the same time).
LinkedList (still) follows "primitive charm" strategy. So it does not try to add/append new data to/after Nil
, to have possible result like this: {Nil, newElement}. (After all Nil
should be last element)
Of course it could check if
list is empty then put addingList
to the beginning and Nil
to the end. But this would be "too smart", I guess.
But, anyway append()
returns "expecting" result Like this:
val addingList = new LinkedList[String]("a", "b")
val result = emptyList append addingList
result = {"a", "b"}.
In this case it returns 'addingList' itself, and/but does not change initial list.
If we try to assign newElement to the next
ref:
emptyList.next = LinkedList("whatever")
As result we would have emtyList changed like this:
LinkedList(null, whatever)
I.e. it creates fist element as null, since we have used next()
assigning new/next element to it. So it moves Nil to the end, because first element which is null, has next reference to new element we added (addingElelement
).
Because
"the "emptyList" is also the "head" link"
and head in our case head is Nil
, but Nill
can not have next, so it has to create new first element (which is has null value) with next() referece to our new addingElelement
.
Personally I find it "too much primitive" and not "so much elegant". But it depends, I guess.
Task oriented story:
For my initial task (why I start thinking about this 'strange' list behaviour [even though it's mutable]) -- I wanted to use mutable list for a class/object called Dictionary
which would keep Words
in it (dictionary by default has not any words). And I would have methods like addWord(wod:String)
for adding new words. For now my implementation will be changed (I'm not going to use this LinkedList
, but rather MutableList
. It seems it is more mutable than previous one):
object Dictionary {
val words = new mutable.MutableList[Word]();
def addWord(word: Word): Unit = {
words += word;
}
}
But possible implementation could be like this:
object Dictionary {
var words = new mutable.LinkedList[Word]();
def addWord(word: Word): Unit = {
if (words.isEmpty) {
words = words append( mutable.LinkedList[Word](word) ) // rely on append result
} else {
words append( mutable.LinkedList[Word](word) )
}
}
}
But then I have to use var
instead of val
, and I should transform every new Word to LinkedList
, and my logic became more complicated.
Source: stackoverflow.com
Related Query
- scala append to a mutable LinkedList
- How to append or prepend on a Scala mutable.Seq
- Scala - mutable (var) method parameter reference
- mutable vs. immutable in Scala collections
- Which scala mutable list to use?
- How to append or prepend an element to a tuple in Scala
- Scala - Mutable thread safe collections
- How to use mutable collections in Scala
- How can I avoid mutable variables in Scala when using ZipInputStreams and ZipOutpuStreams?
- Scala 2.11 LinkedList is deprecated, what should I use?
- What is the proper way to remove elements from a scala mutable map using a predicate
- Can't append to scala's mutable LinkedList?
- What is the easiest way to deeply clone (copy) a mutable Scala object?
- No Scala mutable list
- Scala mutable collections and "Reference must be prefixed warnings"
- When to use mutable vs immutable classes in Scala
- Unmodifiable view of a mutable Scala collection
- Scala mutable BitSet, where are the mutating operations?
- scala dynamic multi dimensional mutable arrays like datastructures
- Can you sort a mutable Scala collection in place?
- How to use mutable and immutable Sets in the same file, in Scala
- Scala uses mutable variables to implement its apis
- scala mutable val List
- Migrating a generic append function to Scala 2.13 collections
- If scala advocate immutability why it adopted actor model with its mutable nature?
- Scala Immutable Set is Mutable when declaring as a var
- Update a mutable map with default value in Scala
- Append Map(key, Set[value]) in a Map to existing Key in Scala 2.11
- Scala Mutable Option?
- Why exactly is prepend to a Scala List a constant time operation, but append a linear time operation?
More Query from same tag
- Scala and Spark : how to go through an image?
- Scala Swing Date Picker
- How do I configure scalafx
- Scala - Get last two characters from string
- Generic Action in Play Framework controller
- How design a Specs2 database test, with interdependent tests?
- Intellij not finding packages
- Scala - mutable (var) method parameter reference
- Scaldi : Bind[T < AkkaInjectable] to TestProbe.ref
- Adding and removing callbacks in Scala
- Search using Thread in Lucene 6.2 using Scala
- Lazy formatted recursive JSON type can't be found as implicit value
- Difficulty Training and Evaluating Neural Network Using DL4J, ND4J and Spark
- Load a class at run time in a scala project
- Task not Serializable error:Spark
- Spark on Yarn Resource Management on Amazon EMR: How to utilize all available cores for spark job execution
- Maximize a exponential equation using scalanlp breeze optmize library
- Why sometimes the scala compiler interpret in a different way white spaces and dots
- Why did the scala compiler not flag what appears to not be a tail-recursive function?
- Is it possible to correctly calculate SVD on IndexedRowMatrix in Spark?
- Why can't I specify a result type for an anonymous function in Scala?
- Scala pattern match multiple types
- Best approach to divide the single column into multiple columns Dataframe Spark Scala
- Speed up collaborative filtering for large dataset in Spark MLLib
- Expand Column to many rows in Scala
- Scala Generic Subtypes and Cake Pattern
- How to merge an Object and non-object-valued in HOCON?
- Sbt update shows Server access Error: java.security.ProviderException: java.lang.NegativeArraySizeException
- Index routes in Scala Play Framework 2.5.x
- How to read records in JSON format from Kafka using Structured Streaming?