|
16 | 16 | import java.util.ArrayList; |
17 | 17 | import java.util.Collection; |
18 | 18 | import java.util.List; |
| 19 | +import java.util.RandomAccess; |
19 | 20 |
|
20 | 21 | /** |
21 | 22 | * A partial implementation of the {@link MessageLite} interface which implements as many methods of |
@@ -343,19 +344,36 @@ private static <T> void addAllCheckingNulls(Iterable<T> values, List<? super T> |
343 | 344 | ((ArrayList<T>) list).ensureCapacity(list.size() + ((Collection<T>) values).size()); |
344 | 345 | } |
345 | 346 | int begin = list.size(); |
346 | | - for (T value : values) { |
347 | | - if (value == null) { |
348 | | - // encountered a null value so we must undo our modifications prior to throwing |
349 | | - String message = "Element at index " + (list.size() - begin) + " is null."; |
350 | | - for (int i = list.size() - 1; i >= begin; i--) { |
351 | | - list.remove(i); |
| 347 | + if (values instanceof List && values instanceof RandomAccess) { |
| 348 | + List<T> valuesList = (List<T>) values; |
| 349 | + int n = valuesList.size(); |
| 350 | + // Optimisation: avoid allocating Iterator for RandomAccess lists. |
| 351 | + for (int i = 0; i < n; i++) { |
| 352 | + T value = valuesList.get(i); |
| 353 | + if (value == null) { |
| 354 | + resetListAndThrow(list, begin); |
| 355 | + } |
| 356 | + list.add(value); |
| 357 | + } |
| 358 | + } else { |
| 359 | + for (T value : values) { |
| 360 | + if (value == null) { |
| 361 | + resetListAndThrow(list, begin); |
352 | 362 | } |
353 | | - throw new NullPointerException(message); |
| 363 | + list.add(value); |
354 | 364 | } |
355 | | - list.add(value); |
356 | 365 | } |
357 | 366 | } |
358 | 367 |
|
| 368 | + /** Remove elements after index begin from the List and throw NullPointerException. */ |
| 369 | + private static void resetListAndThrow(List<?> list, int begin) { |
| 370 | + String message = "Element at index " + (list.size() - begin) + " is null."; |
| 371 | + for (int i = list.size() - 1; i >= begin; i--) { |
| 372 | + list.remove(i); |
| 373 | + } |
| 374 | + throw new NullPointerException(message); |
| 375 | + } |
| 376 | + |
359 | 377 | /** Construct an UninitializedMessageException reporting missing fields in the given message. */ |
360 | 378 | protected static UninitializedMessageException newUninitializedMessageException( |
361 | 379 | MessageLite message) { |
|
0 commit comments