简体   繁体   English

如何在JAVA中的泛型类中使用重写方法

[英]How to use override method in generic class in JAVA

I don't want to damage to polymorphism by generic. 我不想用泛型破坏多态性。 But my short thought compels casting. 但是我的想法很短,迫使铸造。 When i didn't do that, the eclipse regarded a equals method as of Object Class. 当我不这样做时,日食将Object类视为equals方法。 Anyone has good solution?? 任何人都有好的解决方案?? The Problem is in if statement of ArraySet Class. 问题出在ArraySet类的if语句中。 Good luck. 祝好运。

public class Star {

    (...)

     // Public Method
     @Override
     public boolean equals(Object anObject) { (...) }

}

public class ArraySet<E> {

    // Instance Variables
    private E[] _elements;
    (...)

    // Constructors
    @SuppressWarnings("unchecked")
    public ArraySet() {
        this._size = 0;
        this._maxSize = ArraySet.DEFAULT_MAX_SIZE;
        this._elements = (E[])new Object[this._maxSize];
    }

    (...)

    **if(((Star)this._elements[i]).equals(anElement))**

    (...)
}

public class AppController {

    // Instance Variables
    private AppView _appView;
    private ArraySet<Star> _starCollector;

    // Constructor
    public AppController() {
        this._appView = new AppView();
        this._starCollector = new ArraySet<Star>();
    }
    (...)
}

postscript: I'm studying English. 后记:我正在学习英语。 So thanks for your pointing out. 因此,感谢您的指出。

I don't want to damage to polymorphism by generic. 我不想用泛型破坏多态性。

You are not damaging polymorphism. 不会破坏多态性。 Casting will break the whole point of using generics. 强制转换将破坏使用泛型的全部目的。

Here: 这里:

 if(((Star)this._elements[i]).equals(anElement))

you don't need to cast this._elements[i] to Star . 您无需将this._elements[i]Star Just call equals directly on this._elements[i] : 只需在this._elements[i]上直接调用equals

 if(this._elements[i].equals(anElement))

the eclipse regarded a equals method as of Object Class eclipse视为Object类的equals方法

No it does not. 不,不是的。 When you do this._elements[i].equals(anElement) , at runtime, the type of this._elements[i] will be figured out and it will call the equals method on whatever type it is, instead of Object . 当您执行this._elements[i].equals(anElement)时,将在运行时确定this._elements[i]的类型, this._elements[i]以任何类型(而不是Object调用equals方法。 Basically, your Star 's equals method will be called even if you don't cast it. 基本上,即使不进行强制转换,也会调用Starequals方法。

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

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