Why do we have contains(Object o) instead of contains(E e)?

前端 未结 5 1415
广开言路
广开言路 2020-12-18 20:21

Is it to maintain backwards compatibility with older (un-genericized) versions of Collection? Or is there a more subtle detail that I am missing? I see this pat

5条回答
  •  情歌与酒
    2020-12-18 20:42

    Because otherwise it could have only be compared to the exact match of parameter type, specifically wildcarded collections would have stopped working, e.g.

    class Base
    {
    }
    
    class Derived
      extends Base
    {
    }
    
    Collection< ? extends Base > c = ...;
    
    Derived d = ...;
    
    Base base_ref = d;
    
    c.contains( d ); // Would have produced compile error
    
    c.contains( base_ref ); // Would have produced compile error
    

    EDIT
    For doubters who think that's not one of the reasons, here is a modified array list with a would be generified contains method

    class MyCollection< E > extends ArrayList< E >
    {
        public boolean myContains( E e )
        {
            return false;
        }
    }
    
    MyCollecttion< ? extends Base > c2 = ...;
    
    c2.myContains( d ); // does not compile
    c2.myContains( base_ref ); // does not compile
    

    Basically contains( Object o ) is a hack to make this very common use case to work with Java Generics.

提交回复
热议问题