On Mon, 10 Apr 2023 05:12:07 GMT, Tingjun Yuan <[email protected]> wrote:
>> If you really don't trust a collection, then we can't do anything.
>>
>> Can copying the results of `toArray` ensure accuracy and security? It has
>> too many possible problems. Maybe the size of the array is wrong, maybe it
>> forgot to copy the contents of the collection and all it returns is an array
>> full of nulls.
>>
>> To put it one step further, is its iterator necessarily correct? Perhaps its
>> iterator implementation is also incorrect:
>>
>>
>> class BadList implements List<Object> {
>> private Object[] array;
>>
>> // ...
>>
>> public Iterator<Object> iterator() {
>> // crazy implementation
>> return new Iterator<Object>() {
>> int i = 0;
>>
>> public boolean hasNext() {
>> return Math.random() < 0.5;
>> }
>>
>> public Object next() {
>> if (Math.random() < 0.25) {
>> array[i++] = null;
>> return new Object();
>> } else {
>> return array[i++];
>> }
>> }
>> };
>> }
>> }
>>
>>
>> But who cares? Since its implementation is incorrect, it is normal for it to
>> suffer for itself. We only need to prevent errors from being leaked to other
>> places, rather than defending against all errors.
>
> @Glavo Then why doesn't `ArrayList` trust `toArray()`? If all implementations
> behave correctly, then it should return an `Object[]` independent of the
> original collection, so `ArrayList` should trust it. Those who doesn't
> implement `toArray()` correctly should use these methods at their own risk,
> shouldn't they?
>
> This PR modifies a class that is used by nearly every JVM code, so safety is
> more important than performance.
@yuantj As I mentioned earlier, we need to prevent errors from leaking to other
places, rather than defending against all errors.
-------------
PR Comment: https://git.openjdk.org/jdk/pull/13383#issuecomment-1501404519