如何在不知道其真实类型的情况下比较两个对象

发布于 2024-08-26 04:20:58 字数 567 浏览 3 评论 0原文

我必须实现一个单链表,但它应该将对象放在适当的位置。 当我将它与特定类结合使用时,一切都很好,但是当我尝试使其通用并且方法插入的参数是对象时,出现了一些问题。 当我想在正确的位置输入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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖凝香 2024-09-02 04:20:58

您有两个选择:

  • 让每个对象的类实现 java.lang.Comparable 并为每个类编写比较逻辑,然后只接受 Comparable 而不是 Object< /code> 并调用 compareTo()
  • 创建列表的 comparator 属性并在构造时设置它。具体比较器(java.util.Comparator 的实现)应该知道如何比较放入列表的这个特定实例中的对象。

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文