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.
Like I said, rawList contains a reference to stringList, not its contents. When you add all elements of rawList to stringList, you are again adding references to the elements. Afterwards, stringList contains a reference to itself, as that was what originally in rawList.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com