Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope issues concerning conditional assignment for an ArrayList

I'm trying to deal with a number of different cases in my code dependent on attributes pulled from the HTTPRequest object. The thing is, different data gets pulled to fill the ArrayList dependent on the Request stuff, but the format is the same.

if (request.getAttribute("timePeriod").equals(null)) {
    ArrayList<ArrayList<MyWeirdObject>> HM = Test.getGlobalChallenge();
}
else {
    ArrayList<ArrayList<MyWeirdObject>> HM = Test.getGlobalChallengeByMonth(Test);
}

If I don't initialize it before assignment, the code (in a JSP) says - of course - that it can't resolve the HM object.

ArrayList<ArrayList<MyWeirdObject>> HM = new ArrayList<ArrayList<MyWeirdObject>>();
if (request.getAttribute("timePeriod").equals(null)) {
    ArrayList<ArrayList<MyWeirdObject>> HM = Test.getGlobalChallenge();
}
else {
    ArrayList<ArrayList<MyWeirdObject>> HM = Test.getGlobalChallengeByMonth(Test);
}

But if I initialize it, it complains about duplicate local variables. How can I set this to initialize/assign differently based on different situations?

like image 644
rainydaymatt Avatar asked Sep 23 '26 16:09

rainydaymatt


1 Answers

Don't declare the ArrayList again inside the if blocks.

ArrayList<ArrayList<MyWeirdObject>> HM;
if ((request.getAttribute("timePeriod") == null) {
    HM = Test.getGlobalChallenge();
}
else {
    HM = Test.getGlobalChallengeByMonth(Test);
}
like image 111
Mark Byers Avatar answered Sep 25 '26 05:09

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!