Uploaded image for project: 'Commons Lang'
  1. Commons Lang
  2. LANG-1074

Add a method to ArrayUtils for removing all occurrences of a given element

    XMLWordPrintableJSON

Details

    • Improvement
    • Status: Closed
    • Minor
    • Resolution: Implemented
    • 3.3.2
    • 3.5
    • lang.*
    • None

    Description

      Could we add the method: removeElementAll to remove all the occurrences of the specified element from the specified (boolean/char/byte/short/int/long/float/double/Object) array:

      org.apache.commons.lang3.ArrayUtils.java
          public static <T> T[] removeElementAll(final T[] array, final Object element) {
              int index = indexOf(array, element);
      
              if (index == INDEX_NOT_FOUND) {
                  return clone(array);
              }
      
              int[] indices = new int[array.length - index];
              int count = 0;
              indices[count++] = index;
      
              for (;;) {
                  index = indexOf(array, element, ++index);
      
                  if (index == INDEX_NOT_FOUND) {
                      break;
                  } else {
                      indices[count++] = index;
                  }
              }
      
              return (T[]) removeAll((Object) array, Arrays.copyOfRange(indices, 0, count));
          }
      

      or maybe better:

      org.apache.commons.lang3.ArrayUtils.java
         public static <T> T[] removeElement(final T[] a, final Object element, boolean removeAll) {
              int index = indexOf(a, element);
      
              if (index == INDEX_NOT_FOUND) {
                  return clone(a);
              } else if (!removeAll || index >= a.length - 1) {
                  return remove(a, index);
              } else {
                  int[] indices = new int[a.length - index];
                  int count = 0;
                  indices[count++] = index++;
                  
                  for (int len = a.length; index < len; index++) {
      
                      if ((a[index] == null) ? element == null : (element == null ? false : a[index].equals(element))) {
                          indices[count++] = index;
                      }
                  }
      
                  return (T[]) removeAll((Object) a, Arrays.copyOfRange(indices, 0, count));
              }
          }
      

      Attachments

        1. LANG-1074_20150320.patch
          19 kB
          haiyang li
        2. LANG-1074.patch.txt
          19 kB
          haiyang li

        Activity

          People

            dmjones500 Duncan Jones
            lihy70 haiyang li
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: