I have to implement a one linked list bu开发者_开发知识库t 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:
- make each object's class implement
java.lang.Comparableand write the comparison logic for each class there, then just acceptComparableinstead ofObjectand callcompareTo() - create a
comparatorproperty of your list and set it on construction. The concrete comparator (implementation ofjava.util.Comparator) should know how to compare the objects that are put in this particular instance of your list.
加载中,请稍侯......
精彩评论