Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does javax MimeType not implement equals?

Tags:

java

The javax.activation.MimeType class does not compare intuitively (to me) due to a lack of an overridden equals-method. Consider the following snippet;

MimeType a = new MimeType("image/png");
MimeType b = new MimeType("image/png");

a.equals(b);                            // false

a.toString().equals(b.toString());      // true
a.getBaseType().equals(b.getBaseType());// true
a.getSubType().equals(b.getSubType());  // true
a.getParameters().size();               // 0
b.getParameters().size();               // 0

It seems to me that a and b are equal in every aspect and that a.equals(b) should return true.

Is there a reason that this class does not implement an equals-method?

Update: There exists a match-method which does exactly what I want, but I only found out after posting this question which kind-of confirms the not-so-intuitiveness of this class.

like image 620
Joost Avatar asked Mar 30 '17 06:03

Joost


1 Answers

You could consider filing a bug; at a glance this seems like a class that should properly override .equals() and .hashCode(). Of course that won't help you for some time (not sure if this library is on the JDK's release cycle).

As a workaround you could create a subclass or wrapper class that properly implements .equals() and .hashCode(), e.g.:

public class ValueMimeType extends MimeType {
  // constructors

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o instanceof ValueMimeType) { // not MimeType, as that wouldn't be symetric
      return match((ValueMimeType) o);
    }
    return false;
  }

  @Override
  public int hashCode() {
    return toString().hashCode();
  }
}

And just always use ValueMimeType instead of MimeType. Obviously not ideal, but better than nothing.

like image 50
dimo414 Avatar answered Nov 13 '22 03:11

dimo414