-
Enhancement
-
Resolution: Unresolved
-
P5
-
6u26
-
Fix Understood
-
x86
-
windows_7
A DESCRIPTION OF THE REQUEST :
The method Collections.sort could be made more general by allowing it to handle Lists which may (or may not) have been generated via a call to Collections.singletonList(T). Currently this will throw an UnsupportedOperationException.
By comparison, Collections.sort does work when passed the result of calling Collections.emptyList(). So you could say the method fails to enforce the "contract", whereby the javadoc states "The specified list must be modifiable..."
The contract of Collections.sort(List) could become to simply return the original list if it has size <= 1. Then, only lists of size 2 or greater need be modifiable.
JUSTIFICATION :
User code might contain, for example, this pattern:
List<T> items = generate();
Collections.sort(items);
The implementation of generate() is currently free to return various types of List: LinkedList, ArrayList; and in "corner cases" might return Collections.emptyList().
It would be nice if generate() was also free to return Collections.singletonList() for certain corner cases.
---------- BEGIN SOURCE ----------
import java.util.Collections;
import java.util.List;
public class CollectionsTest {
public static void main(String[] args) {
List<String> one = Collections.singletonList("item");
Collections.sort(one);
System.out.println(one);
}
}
---------- END SOURCE ----------
The method Collections.sort could be made more general by allowing it to handle Lists which may (or may not) have been generated via a call to Collections.singletonList(T). Currently this will throw an UnsupportedOperationException.
By comparison, Collections.sort does work when passed the result of calling Collections.emptyList(). So you could say the method fails to enforce the "contract", whereby the javadoc states "The specified list must be modifiable..."
The contract of Collections.sort(List) could become to simply return the original list if it has size <= 1. Then, only lists of size 2 or greater need be modifiable.
JUSTIFICATION :
User code might contain, for example, this pattern:
List<T> items = generate();
Collections.sort(items);
The implementation of generate() is currently free to return various types of List: LinkedList, ArrayList; and in "corner cases" might return Collections.emptyList().
It would be nice if generate() was also free to return Collections.singletonList() for certain corner cases.
---------- BEGIN SOURCE ----------
import java.util.Collections;
import java.util.List;
public class CollectionsTest {
public static void main(String[] args) {
List<String> one = Collections.singletonList("item");
Collections.sort(one);
System.out.println(one);
}
}
---------- END SOURCE ----------
- relates to
-
JDK-8015708 Collections.sort creates a temporary array even for elements of size 1
-
- Open
-