How can I make an interface instance method accept arguments of the same class only?

前端 未结 3 609
一整个雨季
一整个雨季 2020-12-30 11:45

I want to use an interface like this :

public interface ResultItem {
    public int getConfidence();
    public boolean equals(ResultItem item);
    public R         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 12:39

    Not really an answer to your question, but an important remark (I think):

    If you want your equals-method to be usable for objects in collections and similar, you need to implement public boolean equals(Object o), and it should work for comparisons to all kinds of objects (in most cases returning false, though). You may have additionally a method with a narrower parameter type, and in implementations delegate like this:

    public class IntResult {
        public boolean equals(Object o) {
            return o instanceof IntResult &&
                 this.equals((IntResult)o);
        }
        public boolean equals(IntResult that) {
            // TODO
        }
    
    }
    

    Make sure you comply to all the conditions in the contract of equals, namely symmetry, reflexivity, transitivity and having a compatible hashCode implementation.

提交回复
热议问题