Contents Of Collection Are Updated But Never Queried

Problem

You might have seen a warning message similar to Contents of collection are updated but never queried or more specifically Contents of collection ‘collection variable name’ are updated but never queried.

So the collection variable may be any instance of an collection API, for example, List, Set, or even Map.

Let’s take an example as shown below, so you have declared an ArrayList:

List<Object> objects = new ArrayList<>();

Now you add some elements to the above ArrayList:

objects.add(new Object());
objects.add(new Object());

You may need to set attributes of the object either through constructor or setter methods before you add the instance of your actual Object to the ArrayList.

So you have defined ArrayList but if you have not removed element from the above ArrayList variable objects later anywhere in your program. In such situation you will see a warning message as I have specified in the beginning of the tutorial.

Therefore when you define a collection there should be no problem, but when you add element to the collection but there is no corresponding remove operation then a warning message Contents of collection ‘collection variable name’ are updated but never queried is shown.

Solution

So the best way to get rid of such warning message is to call method(s) associated with the collection.

For example, you can query the collection to get the size of the collection using size() method – objects.size(), or any method which you think you need to call on this collection.

Or even you can define your own method for your collection and you call it somewhere else to get rid of such warning message.

Leave a Reply

Your email address will not be published. Required fields are marked *