Writing contains() for a generic collection

后端 未结 4 1392
北海茫月
北海茫月 2020-12-18 10:42

I\'m writing a skiplist class in java as an excercise. I\'ve written a class called SkipListInternal which contains the actual skiplist. I\'ve also mad

4条回答
  •  太阳男子
    2020-12-18 11:09

    Strictly speaking such an implementation would be wrong.

    The reason for this is that even if an object is not of type E, it could still return true on an equals() call.

    Assume for a second, that you've got a class like this:

    public class FakeString {
      private final String value;
    
      public FakeString(String value) {
        if (value == null) {
          throw new IllegalArgumentException();
        }
        this.value = value;
      }
    
      public int hashCode() {
        return value.hashCode();
      }
    
      public boolean equals(Object o) {
        return value.equals(o);
      }
    }
    

    Then this code would print true:

    List strings = Arrays.asList("foo", "bar", "baz");
    System.out.println(strings.contains(new FakeString("bar")));
    

    And just to clarify: this behaviour is intended and is the reason why contains() takes an Object instead of E. The same is true for remove(), by the way.

提交回复
热议问题