You first add
stringList to
rawList. You then add everything that is in
rawList to
stringList. That includes
stringList itself. In other words,
stringList.contains(stringList). At this moment,
stringList is no longer
[b, c] but
[b, c, a, 10, <stringList itself>, 20].
If you print out
stringList, it will call
toString() on
stringList. This in turn calls
toString() on all of the elements. One of these elements is
stringList itself. The
(this Collection) part is there to prevent toString() to be called again, and again, and again, until you get a StackOverflowError.
Remember, in
Java, variables are references (or primitives). When you add
stringList to
rawList you don't add its contents but the reference to the very same object. To get the result you want, you must add a
copy of
stringList to
rawList. There are two ways:
1)
rawList.add(stringList.clone()). This will only work if
stringList is declared as a LinkedList, ArrayList or any other type that has a public clone() method. If you would declare both as
List instead this would not work.
2)
rawList.add(new ArrayList(stringList)) or
rawList.add(new LinkedList(stringList)). This will create a new list with the same contents as
stringList, and this new list is added to
rawList.
Note that your code has a serious flaw. You suppress the warnings, but in this case that's unjustified. I can make your code throw an exception by adding just one line:
That's because your LinkedList<
String> not only contains Strings, but also Integers and a LinkedList.