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
}
//...
}
You have two options:
java.lang.Comparable
and write the comparison logic for each class there, then just accept Comparable
instead of Object
and call compareTo()
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.