java为什么等于方法输入参数为Object [英] java why should equals method input parameter be Object

查看:263
本文介绍了java为什么等于方法输入参数为Object的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读一本关于数据结构的书.目前,我正在使用图形,以下代码用于图形的顶点部分.

I'm going through a book on data structures. Currently I'm on graphs, and the below code is for the vertex part of the graph.

class Vertex<E>{
    //bunch of methods

    public boolean equals(Object o){
         //some code
    }
}

当我尝试实现此equals方法时,我的编译器抱怨没有检查参数的类型,而只是允许向其发送任何对象.对于我来说,为什么该参数不应该是顶点"而不是对象",这似乎也让我有些奇怪.作者这样做有什么原因吗?或者这是一个错误或过时的例子吗?

When I try to implement this equals method my compiler complains about not checking the type of the parameter and just allowing any object to be sent it. It also does seem a bit strange to me why that parameter shouldn't be a Vertex instead of an Object. Is there a reason why the author does this or is this some mistake or antiquated example?

推荐答案

@Override
public boolean equals(Object obj)
{
     if(obj == null) return false;
     else if (!(obj instanceof Vertex)) return false;
     else return // blah blah
}

这篇关于java为什么等于方法输入参数为Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆