简体   繁体   English

如果重写equals()方法,是否可以在Java中比较对类实例的引用?

[英]Is it possible in Java to compare references to instances of class if equals() method is overridden?

I need to compare 2 instances of a class, that has equals method overridden - it returns string that equal concatenation of parameters. 我需要比较一个类的2个实例,它equals方法重写 - 它返回等于参数串联的字符串。 But I need be sure that exists only 1 instance. 但我需要确定只存在一个实例。 For this I think to check references. 为此,我想检查一下参考文献。

Is it possible in java? 在java中有可能吗?

Use == to compare the references. 使用==来比较引用。 It's enough to make sure if different variables refer to the same instance. 这足以确保不同的变量是否引用同一个实例。

The easy way to ensure that only one instance exists is to use an Enum. 确保只存在一个实例的简单方法是使用Enum。

public enum MyEnum {

    NameOfSingleton("aPropertyValue");

    private String aProperty;

    private MyEnum(String aProperty) {
        this.aProperty = aProperty
    }

    public getAProperty() {
        return this.aProperty;


}

Using it is just as simple. 使用它就是这么简单。

MyEnum.NameOfSingleton.getAProperty();

This doesn't really address your equality question, but it addresses your need for a singleton instance of a class. 这并没有真正解决您的平等问题,但它解决了您对类的单例实例的需求。

I'm not entirely sure what you're trying to do, but if you need to ensure that only one instance of something exists then you can use the static keyword to do so. 我不完全确定你要做什么,但是如果你需要确保只存在一个实例,那么你可以使用static关键字来实现。 There are multiple ways you could ensure this with static, for instance creating a static variable called count that keeps track of how many instances of the object have been made. 有多种方法可以通过静态确保这一点,例如创建一个名为count的静态变量,用于跟踪对象的实例数。 Then in the constructor for the object you just increment count. 然后在对象的构造函数中,您只需递增计数。 To see if there is more than one instance of the object you just check the count variable and it should tell you. 要查看是否有多个对象实例,您只需检查计数变量,它应该告诉您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM