vigna / fastutil

fastutil extends the Java™ Collections Framework by providing type-specific maps, sets, lists and queues.
Apache License 2.0
1.78k stars 196 forks source link

`singleton` equals may lead to `java.lang.ClassCastException` #308

Open catap opened 11 months ago

catap commented 11 months ago

A trivial example:

ShortSets.singleton((short) 1).equals(IntSets.singleton(1));

fails as:

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Short (java.lang.Integer and java.lang.Short are in module java.base of loader 'bootstrap')

    at it.unimi.dsi.fastutil.shorts.ShortCollection.contains(ShortCollection.java:134)
    at it.unimi.dsi.fastutil.shorts.AbstractShortCollection.contains(AbstractShortCollection.java:82)
    at java.base/java.util.AbstractCollection.containsAll(AbstractCollection.java:309)
    at it.unimi.dsi.fastutil.shorts.AbstractShortCollection.containsAll(AbstractShortCollection.java:154)
    at it.unimi.dsi.fastutil.shorts.AbstractShortSet.equals(AbstractShortSet.java:38)
vigna commented 11 months ago

Mmmhh. That's somehow a fault along the whole library—if you use the object-based methods, what they try to do is a class cast to the parameter of the class and then delegate to the primitive value. contains() methods should do something smarter, that is, returning false if the object is not an instance of the parameter of the class, and then trying the delegation.

Thinking of it, it is really weird nobody ever noticed this problem before, even outside this specific case. I guess the fix is to fix contains().

catap commented 11 months ago

@vigna yes, it fails on all library, indeed.