StringList Manipulation

I’m trying to manipulate the contents of a StringList for use in one place in the code while leaving the original list intact. I’m finding this doesn’t work. I’m guessing that the StringList is being maintained by ‘reference’ somehow and when I tweak the copy it changes the original as well. Thoughts on how to force Processing to create new StringList object that isn’t ‘linked’

see code snippet:
it removes the first entry ("") and adds empty ("") last entry.

StringList tweakList(StringList orig) {
  StringList result = new StringList();
  result = orig;
  result.append("");
  result.remove(0);
  return result;
}
  List lst = Arrays.asList(tweakList(imgAttributes).array());
  println(".........");  
  println("Attributes 'lst' list: " + lst);
  println(".........");  
  print("imgAttributes after tweekList() " );
  printArray(imgAttributes);

This is what I see in the results console
(first result below is from an earlier ‘print’ call)

imgAttributes file at build..........
StringList size=9 [ "", "bob", "phil", "anni", "may", "fido", "rover", "meow", "puss" ]
.........
Attributes 'lst' list: [bob, phil, anni, may, fido, rover, meow, puss, ]
.........
imgAttributes after tweekList() StringList size=9 [ "bob", "phil", "anni", "may", "fido", "rover", "meow", "puss", "" ]

The entry is moved as needed, but the the underlying StringList “imgAttributes” is modified… even though I’ve not worked on it, at least ‘directly’.
Is there another operator other than ‘=’ that I should be using in ‘result = orig;’ assignment?

Note that your first line of code here has no effect on whether the list is a copy or not. You’re basically saying “point result to a new list, nevermind point it to the parameter list”.

To understand what’s going on better, I recommend reading this:

https://javaranch.com/campfire/StoryCups.jsp

And then this:

https://javaranch.com/campfire/StoryPassBy.jsp

Anyway, the best way to answer questions like this is by looking at the Processing JavaDocs. Find the StringList class and look for useful functions. Specifically, it contains a copy() function that sounds like what you’re looking for.

1 Like

Some cloning insights: :grinning:

Thanks
replacing

StringList result = new StringList(); 
result = orig;

with

StringList result = orig.copy();

did the trick.
Populates the new StringList with the contents of the original (not a pointer to original)