user2826864
user2826864

Reputation: 3

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.

Upvotes: 0

Views: 60

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504092

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));

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

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

After this point you have discarded the ArrayList you created in the first statement, and now resultUrls is a reference to the public variable that is a member of the object referenced by webPages.

You should be able to figure it out from this point.

Hint: the last statement above should be

resultUrls.addAll(webPages.getUrls());

Upvotes: 2

Related Questions