RFR 7065380 : Allow Collections.sort to sort Collections.singletonList() result
Mike Duigou
mike.duigou at oracle.com
Sat Mar 10 01:39:06 UTC 2012
On Mar 1 2012, at 13:35 , Jason Mehrens wrote:
> What about exception cases where the single element is not comparable? http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045147
>
> Consider the following:
>
> =========
> Object[] a = new Object[]{new Object()};
> Arrays.sort(a);
> List l = Arrays.asList(a); //Evil raw type
> Collections.sort(l);
> ========
>
> On JDK1.6u31, Arrays.sort passes but, Collections.sort fails with a class cast.
>
> Per the method contracts, both Arrays.sort and Collections.sort should fail in non-comparable single element case.
Correct. This would require extra checks. If we do add these checks would it be reasonable to add them as assertions to reduce "but you made it slower" calls?
I'm not really confident about proposing "assertions as lint detection" rather than adding explicit checks. We wouldn't (and don't) use optional assertions for array bounds checking. This has clearly been the right choice. I'm still considering my feelings about whether to be hardline and suggest we add the checks to Arrays.sort
Thoughts anyone?
> So for this patch, the length check be performed to prevent the element swap that causes the unsupported operation exception but not prevent the call to Arrays.sort. That way both methods always have the same type checking behavior.
Yes, this patch would result in the above working for both the Arrays.sort and Collections.sort cases, but as you point out, in technical breach of the contract of both.
Mike
> Jason
>
>
> > From: mike.duigou at oracle.com
> > Subject: RFR 7065380 : Allow Collections.sort to sort Collections.singletonList() result
> > Date: Thu, 1 Mar 2012 11:50:49 -0800
> > To: core-libs-dev at openjdk.java.net
> >
> > Hello all;
> >
> > Currently Collections.sort() refuses to sort the lists which result from calling Collections.singletonList(). This makes some sense because the singleton lists are immutable but they are also alway sorted.
> >
> > This patch allows Collections.sort() to be used with empty and singleton lists of all types. A short circuit return is provided for lists of length 0 and 1 as they are already sorted.
> >
> > WEBREV: http://cr.openjdk.java.net/~mduigou/7065380/0/webrev/
> >
> > For the unit test ignore the diffs and view the "New" file--webrev doesn't understand "hg copy".
> >
> > Thanks,
> >
> > Mike
More information about the core-libs-dev
mailing list