0

i was looking for a way to "automate" all the casting needed to have List operations available for plain arrays. the issue is that

public static Object[] arrayRemoveAll(Object[] oA, Object[] removeA) {
    List<Object> l = new ArrayList<Object>(Arrays.asList(oA));
    l.removeAll(Arrays.asList(removeA));
    return l.toArray(new Object[l.size()]);
}

always gives me ClassCastException when i try to cast the object back into its original array type (e.g. if i call (String[])arrayRemoveAll(strA, strA2)).

i understand why this happens, but is there any neat way to circumvent this? i would love to be able to use a general function for some of the standard List operations.

thanks a lot in advance.

dotwin
  • 1,302
  • 2
  • 11
  • 31

3 Answers3

1

How about

public static <T> T[] arrayRemoveAll(T[] oA, Object[] removeA) {
    List<T> l = new ArrayList<T>(Arrays.asList(oA));
    l.removeAll(Arrays.asList(removeA));
    return l.toArray(Arrays.copyOf(oA, l.size()));
}

Personally, I'd avoid the cost overhead of all the conversions to list and manually write my loops, though. It does not get that much more verbose.

Also, if you are already using Commons Lang, it has ArrayUtils#removeElements.

Thilo
  • 257,207
  • 101
  • 511
  • 656
0

You could use generics. For example:

@SuppressWarnings("unchecked")
public static <T> T[] arrayRemoveAll(T[] oA, T[] removeA) {
    java.util.List<T> l = new ArrayList<T>(Arrays.asList(oA));
    l.removeAll(Arrays.asList(removeA));
    Class<T> clazz = (Class<T>)removeA.getClass().getComponentType();
    return l.toArray((T[]) Array.newInstance(clazz, l.size()));
}
Pedro Boechat
  • 2,446
  • 1
  • 20
  • 25
  • 1
    Just tested the code above, it compiled and runned fine. I guess the only negative thing with it is the unchecked casts... – Pedro Boechat Nov 21 '12 at 02:40
  • It compiles for me as well... Didn't go as far as testing it. – jahroy Nov 21 '12 at 02:41
  • Oh I have tried to give another way to workaround your original problem :P – Adrian Shum Nov 21 '12 at 02:45
  • You don't even need the second parameter of the newInstance(..) to be l.size(). It could be 0. But if you use the correct size of the new array, people say it will perform faster (http://stackoverflow.com/questions/727627/what-to-pass-to-the-arrays-instance-method-toarrayt-a-method). – Pedro Boechat Nov 21 '12 at 02:50
0

You can't cast the Object[] to another array type because, as you know, arrays don't extend Object[]. However, you can loop through the array and cast each element back to the original type.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268