Remove any occurrence of a given value from an array. The resulting array may be shorter in length, but the relative position of all other items will remain unchanged. This algorithm is robust to null . The items array may contain null values and the item<
(T[] items, T item)
| 432 | * @return |
| 433 | */ |
| 434 | public static <T> T[] removeAll(T[] items, T item) { |
| 435 | int count = 0; |
| 436 | // First, determine the number of elements which will be removed |
| 437 | for (int i = 0; i != items.length; ++i) { |
| 438 | T ith = items[i]; |
| 439 | if (ith == item || (item != null && item.equals(ith))) { |
| 440 | count++; |
| 441 | } |
| 442 | } |
| 443 | // Second, eliminate duplicates (if any) |
| 444 | if (count == 0) { |
| 445 | // nothing actually needs to be removed |
| 446 | return items; |
| 447 | } else { |
| 448 | T[] nItems = Arrays.copyOf(items, items.length - count); |
| 449 | for(int i=0, j = 0;i!=items.length;++i) { |
| 450 | T ith = items[i]; |
| 451 | if (ith == item || (item != null && item.equals(ith))) { |
| 452 | // skip item |
| 453 | } else { |
| 454 | nItems[j++] = ith; |
| 455 | } |
| 456 | } |
| 457 | return nItems; |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | /** |
| 462 | * A default operator for comparing arrays |
no test coverage detected