java - Using a collection reference as an if statement condition without a comparison? -


i'm little embarrassed asking because i'm sure basic question having searched , thought still can't work out.

the code class tutor walked through developing during tutorial on collections course. class represents crime sheet of districts associated crime codes. sheet implemented sortedmap keys of type string (representing district) , values arraylist of integers (representing crime codes).

there 1 method didn't manage finish during tutorial tutor sent on copy of , can't follow logic. code method below

/**  * displays districts affected given crime code  *   *     @param integer crime code  *     @return     none  */ public void displayaffecteddistricts(integer crimecode) {     arraylist<integer> searchcode;     for(string eachdistrict:  crimetable.keyset())     {         searchcode = new arraylist<integer>();         searchcode.add(crimecode);         if(!(searchcode.retainall(crimetable.get(eachdistrict))))         {            system.out.println("code "+crimecode+" found in district "+eachdistrict);          }      } } 

i've run code , can see works can't follow logic of if condition.

my understanding searchcode.retainall(crimetable.get(eachdistrict)) evaluate reference list searchcode , that, @ point, searchcode contain single value given crimecode argument if map entry eachdistrict has crimecode in it's set of values or otherwise empty.

as far i'm aware that's not boolean value can't used if condition without comparison operator.

could please explain i'm missing?

it's pretty bad code. but, here's how works:

the retainall() method returns true if list changed because of operation. list created contains target code, , if other list contains it, list not change.

i severely mark down person wrote if marking it, because it's obtuse. here's better implementation, uses less code, straightforward , easy understand , performs better too:

public void displayaffecteddistricts(integer crimecode) {     (string eachdistrict : crimetable.keyset()) {         if (crimetable.get(eachdistrict).contains(crimecode)) {            system.out.println("code "+crimecode+" found in district "+eachdistrict);         }      } } 

but can improved upon, using less code and performs better:

public void displayaffecteddistricts(integer crimecode) {     (map.entry<string, arraylist<integer>> entry : crimetable.entryset()) {         if (entry.getvalue().contains(crimecode)) {            system.out.println("code "+crimecode+" found in district "+entry.getkey());         }      } } 

this last version avoids numerous calls get(). elite way of coding it. suggest teacher, way should find job.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -