List updating unexpectedly

I have a list that is unexpectedly updating. I have a function that returns a list. I want to call it twice with different parameters and store the results in a single long list.

List<URL> resultUrls = new ArrayList<URL>();
webPages.runSearch(parameter1);                   // runs search and stores result in a public variable of the object webPages
resultUrls = webPages.getUrls();                  // returns public variable
webPages.runSearch(parameter2);
resultUrls.addAll(webPages.getUrls());

Prior to executing the last line, resultUrls already contains the updated results from runSearch using parameter2. I want it to still hold the results from runSearch with parameter1. The net result is that I get two copies of the search using parameter2 appended to each other. What I want is the search using parameter1 appended with the search from parameter2 stored in the resultUrls variable.

Any help would be most appreciated.

Jon Skeet
people
quotationmark

We don't know what webPages is, but I suspect the problem is that your runSearch method doesn't create a new list - it just mutates the existing one. I suspect you want to create a copy of the first list. Note that you don't need the original ArrayList<URL> you were creating, as you were discarding it anyway.

webPages.runSearch(parameter1); 
List<URL> resultUrls = new ArrayList<URL>(webPages.getUrls());
webPages.runSearch(parameter2);
resultUrls.addAll(webPages.getUrls());

(You could start with an empty list and just add the results of webPages.getUrls() after the first call, but it seems a little pointless.)

I suggest you actually change your design, however, so that the type of webPages isn't stateful anyway - instead, make runSearch return the relevant list. At that point, you can have:

List<URL> resultUrls = webPages.runSearch(parameter1);
resultUrls.addAll(webPages.runSearch(parameter2));

people

See more on this question at Stackoverflow