0

I have the following code snippet:

Set<Short> map=new HashSet<>();
short i=1;
map.add(i);
map.remove(i-1)

It ignores removal because I-1 was automatically casted to integer. But, why there is no remove(V) method with generic? It's bad, I should see an exception or this method should be generic. Doesn't make any sense. Why was it designed this way?

The question is:

If we have Set, why don't we have method remove(E e) inside it? I found that it's because internally there is an array of Object. But why? If we have Set of E generic type, why don't we have E[] as internal storage? For me it's absolutely doesn't make sense.

For example I expected:

class Set<E>{
   private E[] values;

   public void add(E e);

   public void remove(E e);

}

But I got:

class Set<E>{
   private Object[] values;

   public void add(E e);

   public void remove(Object e);

}

Why not to do this?

class Set<E>{
   private E[] values;

   public void add(E e);

   public void remove(E e){ 
      for(E v:values){
         if(v.equals(e)){
            //remove element
         }
      }
    }
}

????

avalon
  • 2,231
  • 3
  • 24
  • 49
  • 3
    You might want to post code the compiles. Map has no add method. Perhaps you meant List. – Eran Sep 29 '16 at 12:47
  • Your question isn't clear... – brso05 Sep 29 '16 at 12:48
  • Thanks, sorry I meant set – avalon Sep 29 '16 at 12:50
  • 1
    You can try to remove an Object which is not there. – Peter Lawrey Sep 29 '16 at 12:58
  • It's logically that there's no any object of other type than E, so it even should not try to delete object of wrong type – avalon Sep 29 '16 at 12:59
  • one reason is, that the `Collection#remove` method relies on `Object` equality. This equality is defined by `Object#equals(Object)` which doesn´t neccessarly needs to identify two of the same classes as equal. A `String` could potentionally be equal to an instance of `Employee` if the `Employee` class defines it like this in it´s overriden equal method. The remove method just catches on on this. Also the remove method isn´t bound to work with a correct type, whilst on the other hand the `Collection#add` method would potentionally create exceptions when working with a different type. – SomeJavaGuy Sep 29 '16 at 13:02
  • Thanks, but it does not make sense either. All objects extends Object class.And there in equals method defined. What the problem? – avalon Sep 29 '16 at 13:12
  • See updated post. Thanks – avalon Sep 29 '16 at 13:14

0 Answers0