java - When to use Collections vs when to add extra function to a concrete subclass of a list? -
consider following code detect if linkedlist has loop
public boolean hasloop() { node<e> fast = first; node<e> slow = first; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (slow == fast) { return true; } } return false; } if sun microsystems add functionalities (like: detectloop, reverselinkedlist, findif2linkedlist intersect etc) linkedlist.java, how ? note, sun uses node class internal detail (ie private).
a few options can think of ( listed disadvantages of each)
static function 'hasloop' in linkedlist.java ? ( weird, because if want hasloop existing
instance, calllinkedlist.mergesort(instance)ratherinstance.mergesort())non-static function 'hasloop' in linkedlist.java? ( weird because functions
sortbelong collections )subclass linkedlist.java , add new function 'hasloop' ? ( weird because if need add function
findintersection, need create subclass )somehow use collections , add static method 'hasloop(list)', , add additional interfaces linkedlist.java make somehow possible ? ( ugly node private class internal implementation, ,
ptr.nextcannot performed collections. need setters modify statesetnext()etc.)
a loop makes sense in case of linked list among lists. so, such functionality should specific linkedlist. simplest way :
- add instance method linkedlist implementation:
hasloop()
or
make linkedlist implement
loopable<e>whereloopable<e>{ boolean hasloop(); }
Comments
Post a Comment