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)

  1. static function 'hasloop' in linkedlist.java ? ( weird, because if want hasloop existing instance, call linkedlist.mergesort(instance) rather instance.mergesort() )

  2. non-static function 'hasloop' in linkedlist.java? ( weird because functions sort belong collections )

  3. subclass linkedlist.java , add new function 'hasloop' ? ( weird because if need add function findintersection, need create subclass )

  4. somehow use collections , add static method 'hasloop(list)', , add additional interfaces linkedlist.java make somehow possible ? ( ugly node private class internal implementation, , ptr.next cannot performed collections. need setters modify state setnext() 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> where

    loopable<e>{    boolean hasloop(); } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -