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

前端 未结 3 579
一整个雨季
一整个雨季 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:29

    There is a frequently-seen idiom that goes as follows:

    public interface ResultItem<T extends ResultItem<T>> {
        public int getConfidence();
        public boolean equals(T item);
        public T cloneWithConfidence(int newConfidence);
    }
    
    public class IntResult implements ResultItem<IntResult> {
      //...
    }
    
    0 讨论(0)
  • 2020-12-30 12:30

    Well, you could make it generic:

    public interface ResultItem<T extends ResultItem<T>> {
        public boolean equals(ResultItem<T> item);
    }
    

    Then you would need to make IntResult implement ResultItem<IntResult>.

    Of course that doesn't stop another class from misbehaving, e.g. FloatResult implementing ResultItem<IntResult> but it makes various bits of API work when all the classes are well behaved.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题