java - Anything wrong with modify an object inside a loop? -


public collection<queuemetrics> getallgatewayqueuemetricscurrent(string keywords) {     queuemetrics qminput = null;     queuemetrics qmimport = null ;     queuemetrics qmreport = null ;     arraylist<queuemetrics> metrics = new arraylist<queuemetrics>();      (string keyword : keywords.split(",")){         consoleservicembean console = getconsoleservice(keyword);         populatemessagecountstr(qminput, keyword, console, "input");         populatemessagecountstr(qmimport, keyword, console, "import");         populatemessagecountstr(qmreport, keyword, console, "report");     }     metrics.add(qminput);     metrics.add(qmimport);     metrics.add(qmreport);      return metrics; }  private void populatemessagecountstr(queuemetrics qmetrics, string keyword, consoleservicembean console, string type) {     queuemetrics tempmetric = console.getgatewayqueuemetricscurrent(type, keyword);             if( qmetrics == null ){              qmetrics = tempmetric ;     }else{         qmetrics.setpendingmessagecountstr( qmetrics.getpendingmessagecountstr() + ", " + tempmetric.getpendingmessagecount());          }  } 

i tried update qminput, qmimport , qmreport inside upper loop, calling populatemessagecountstr , passing in object updated. in next loop, same object updated 1 more time additional data. however, end result of program qminput, qmimport , qmreport null. knows why? provide more info, when change upper function little bit:

        qminput = populatemessagecountstr(qminput, keyword, console, "input");         qmimport = populatemessagecountstr(qmimport, keyword, console, "import");         qmreport = populatemessagecountstr(qmreport, keyword, console, "report"); 

and lower function returns updated queuemetrics instead of void. program works expcected. knows why original way didn't work? appreciate useful comments.

however, end result of program qminput, qmimport , qmreport null.

because, re-assigning passed queuemetrics reference in method new object if equal null, on first invocation. in case original reference still point null. , hence remain null on further invocation of method, condition qmetrics == null true.

since java passes reference value, re-assigning qmetrics different instance, change value of copy of reference passed. not modify reference value of original reference.

to solve issue, return modified reference method (change return type of populatemessagecounterstr() queuemetrics, , assign original reference on calling side.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -