Andrew Haley wrote:
Marco Trudel writes:
 > Andrew Haley wrote:
 > > Marco Trudel writes:
 > >  > Andrew Haley wrote:
 > >  > > Marco Trudel writes:
 > >  > >  > Andrew Haley wrote:
 > >  > >  > > Marco Trudel writes:
 > >  > >  > >  > Hey guys
> > > > > > > > > > > > > > java.util.Arrays.binarySearch(Object[] a, Object key, Comparator c) > > > > > > > exchanges a[i] and key, this can lead to ClassCastExceptions as shown in > > > > > > > ComparatorTest.java. Arrays.patch fixes it. > > > > > > > > > > > > > > > > > > > > > Changelog suggestion: > > > > > > > > > > > > > > 2006-12-13 Marco Trudel <[EMAIL PROTECTED]> > > > > > > > > > > > > > > * classpath/java/util/Arrays.java (binarySearch(Object[] a, Object key, > > > > > > > Comparator c)):
 > >  > >  > >  >  Fix swapped objects inCollections.compare(...) call.
> > > > > > > > > > > > > > > > > > > > > Comments? > > > > > > > > > > > > I guess I don't get it. Arrays.binarySearch() is defined to be
 > >  > >  > > searching for a key in an array.  The comparator has to be able 
to
 > >  > >  > > compare keys and values.  How is this not a bug in the test case?
> > > > > > > > > > The key might be a different object that the values. The comparator
 > >  > >  > will then be responsible to see if they're equal. Thus the order is
 > >  > >  > important...
> > > > > > > > OK, but where does it say that in the spec? > > > > > > Sorry, I did not read the spec. > > > > What!! > > Shame on me! I was just debugging a ClassCastException on a library and > found that one to be the cause... > > > > This somehow seems logical to me. > > > > But why? Are you assuming that the key _must_ occur on the LHS of the
 > > Comparator?
> > No. The point is that completely different objects might be passed which > have no relation with each other. A stupid example:
 >
 > Object[] o1 = { "22", "23", "24" };
 > Object o2 = new java.awt.Button("2");
> > And then the comparator does: > > public int compare(Object o1, Object o2)
 > {
 >     String s1 = Integer.parseInt((String)o1);
 >     String s2 = ((Button)o2).getName();
 >     return s1.compareTo(s2);
 > }

Here is a quote from the definition of Comparable.compare:

"The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y."

Ah yeah, right... Actually I read that (just forgot it).
Seems like the implementation of compare() is wrong. Funny thing is that this is in a Sun AWT class. So Sun doesn't even follow their own specifications ;-)


Marco

Reply via email to