Sunday, 15 March 2015

java - How to use recursive methods with lists -



java - How to use recursive methods with lists -

i have little problem wrapping head around how utilize recursive methods count number of elements in list, jumping each element in list , count how many elements have stored. seek generalize much possible, utilize illustration of own. info construction have, arraylist have stored elements. of these each have arraylist elements pointing element stored preceding elements id. so: element->list->id (integer, ie. 2)-> element nr.2. want count how many preceding elements there each element, recursive methods. have tried couple of options, storing of preceding elements in new list , give size of number of preceding elements, using counter-int. closest have gotten far using method(id number +1 index located in arraylist containing it):

private int getpredecessorcount(int id){ for(int i:elementlist[id-1].predecessors){ homecoming 1+getpredecessorcount(i); } homecoming 0; }

this gives me right reply elements elements contains list single element. cannot work elements having lists more 1 predecessorelement. ideas?

i tried:

private int getpredecessorcount(int id, int counter) { if(!elementlist[id-1].predecessors.isempty()){ for(int : elementlist[id-1].predecessors){ counter+=getpredecessorcount(i, counter); counter++; } } homecoming counter;

this gives me same result previous one, previous 1 gave me few predecessors ones contained larger lists, 1 gives me wildly many.

ok lets generalise ...

private int counter(list<element> items) { int count = 0; (element item: items) { count ++; // item counting if (item.holdselements) { // inner elements count = count + counter(item.getelements()); } } homecoming count; }

i have intentionally written simplified version of method illustrate how should done. null checks , other border cases ignored purpose.

so count elements in list ... ok simple enough, , if element contains inner items go , count those. homecoming absolute count.

your problem returned result 1 time got count first element, not considering others. problems can spotted utilize of debugger.

java recursion arraylist

No comments:

Post a Comment