views:

92

answers:

1

I have to implement a one linked list but it should put object in appropriate position. Everything was OK when I use it in conjunction with specific class, but when I tried make it universal and argument of method insert was Object some problem appeared. When I want to input Object in right position I should use CompareTo method, but there isn't method in Object class! The problem is how to compare two object elements without known about their real types. Maybe I should use generic class type? But what about CompareTo? Or maybe combine with Element class and place CompareTo there? I suppose it is feasible. :)

public void insert(Object o)
{
   Element el = new Element(o);
   //  initializing and setting iterators

   while(!it.isDone() && ((it.current().getValue())).CompareTo(o)<0) 
                         // it.current() returns Element of List
   {    
      //move interators
   }
//...
}
+5  A: 

You have two options:

  • make each object's class implement java.lang.Comparable and write the comparison logic for each class there, then just accept Comparable instead of Object and call compareTo()
  • create a comparator property of your list and set it on construction. The concrete comparator (implementation of java.util.Comparator) should know how to compare the objects that are put in this particular instance of your list.
Bozho
Good answer. I would recommend making it generic though by class LinkedList<T extends Comparable<T>> { public void insert(T t) { ... } public T get(...) { ... }.
ponzao