Issue to solve: given a family(with an id of type Interger) and all its members(with an int[] comprising all member ids) now we have several families, store them and sort by family members count.
OK, the solution should be to define a class Family which composes the family id and the array of its members.
However, my question is about a not so good solution: a TreeMap is used with the family id as key and members array as value. the code:
class SpeComparator implements Comparator { private Map _ds = null;
SpeComparator speComp = new SpeComparator(); Map map = new TreeMap(speComp); speComp.setDs(map);
int k = 5; for (int i = 0; i < k; i++) { Integer family = new Integer(k - i); int[] members = new int; map.put(family, members); }
this is my previous solution and it doesn't work. try it out you'll see it produces StackOverflowError, I just wonder why this error? I guess in the compare() method the v1, v2 should be both null and there should be an NPE instead of the SOE.
> class SpeComparator implements Comparator { > private Map _ds = null; > > public int compare(Object o1, Object o2) { > int[] v1 = (int[]) _ds.get(o1); > int[] v2 = (int[]) _ds.get(o2); > return v1.length - v2.length; > } > > public void setDs(Map ds) { > this._ds = ds; > } > } > > > int k = 5; > for (int i = 0; i < k; i++) { > Integer family = new Integer(k - i); > int[] members = new int[i]; > map.put(family, members); > } >
There seems to be some nasty looking recursion:
// Declare a New Constructor for SpeComparator
// Which just so happens to hold a Map initially
// its null.
SpeComparator speComp = new SpeComparator();
// a map holding the SpeComparator holding the
// map with a null instance.
Map map = new TreeMap(speComp);
// Set the null instance Map in SpeComparator
// to a New Map that holds this same SpeComparator
// as a Key.
speComp.setDs(map);
To me it appears that there is some nasty recursion that needs fixing. Objects pointing back to themselves, etc, in a very messy manner. I might be wrong though. But StackOverflows are usually thrown when Recursion has gone too deep, and the above explanation is the only one that makes sense to me at the moment.