Friday 28 March 2014

Getting mutable (non-finite) values from a String array.

Problem:

Had a String that I needed to split into Strings by new-line and put into List<String> , afterwards adding more values to the List.

So code looked something like this:
String sentence = "The quick brown fox \n" +
 "jumped over the lazy dog.";
 
List<String> lines = Arrays.asList(sentence.split("\n"));

lines.add("\n" + " ...and the fox escaped.");

But that didn't work. Got an java.lang.UnsupportedOperationException .

The fix:

I found out the problem was that Arrays.asList was returning a finite List, but I needed to add to it. So the work around to that was to make sure the asList was given to an ArrayList which can take your array of Strings[] and turn it into a mutable list.

List<String> lines = new ArrayList(Arrays.asList(sentence.split("\n")));


Context Notes:
This post was from me working with DiffUtils (com.googlecode.java-diff-utils) . Taking lines of text from an original String and detecting the Delta 's and then reapplying the deltas to a "rebuild" String that would match the original as a JUnit test.
This stackoverflow question gave me the answer under "For a Mutable List". 

No comments:

Post a Comment