如何在不知道其真实类型的情况下比较两个对象
我必须实现一个单链表,但它应该将对象放在适当的位置。 当我将它与特定类结合使用时,一切都很好,但是当我尝试使其通用并且方法插入的参数是对象时,出现了一些问题。 当我想在正确的位置输入Object时,我应该使用CompareTo方法,但Object类中没有方法! 问题是如何在不知道两个对象元素的实际类型的情况下比较它们。 也许我应该使用泛型类类型?但是 CompareTo 呢?或者也许与 Element 类结合并将 CompareTo 放在那里? 我想这是可行的。 :)
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
}
//...
}
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
}
//...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有两个选择:
java.lang.Comparable
并为每个类编写比较逻辑,然后只接受Comparable
而不是Object< /code> 并调用
compareTo()
comparator
属性并在构造时设置它。具体比较器(java.util.Comparator
的实现)应该知道如何比较放入列表的这个特定实例中的对象。You have two options:
java.lang.Comparable
and write the comparison logic for each class there, then just acceptComparable
instead ofObject
and callcompareTo()
comparator
property 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.