EDIT 3: this is the cause of the problem:
For removeArrayElement (first version), its returning toArray(new Item[0]), which executes the null element at the end, but with the new method, it returns toArray(arr), which does not execute the null, but you can;t create a generic type array of T, i.e new T[0], so what is a substitute? instead of 'passing the array again' to get rid of the null element at the end
Old problem:
I recently updated how I was handling array sorting by creating one master method (by implements generic types) Only the aftermath method is giving me array out of bounds errors.
Is there anything I've missed?
Old methods:
private static Item[] insertTabItem(Item[] a, int pos, Item item) {
Item[] result = new Item[a.length + 1];
for(int i = 0; i < pos; i++)
result[i] = a[i];
result[pos] = item;
for(int i = pos + 1; i < a.length + 1; i++)
result[i] = a[i - 1];
return result;
}
private static Item[] removeArrayItem(Item[] arr, Item item) {
List<Item> list = new ArrayList<Item>(Arrays.asList(arr));
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == item) {
list.remove(i);
}
}
return list.toArray(new Item[0]);
}
new methods (giving java.lang.ArrayIndexOutOfBoundsException)
public static <T> T[] insertArrayElement(T[] arr, int pos, T item) {
final int N = arr.length;
T[] result = Arrays.copyOf(arr, N + 1);
for(int i = 0; i < pos; i++)
result[i] = arr[i];
result[pos] = item;
for(int i = pos + 1; i < N + 1; i++)
result[i] = arr[i - 1];
return result;
}
public static <T> T[] removeArrayElement(T[] arr, T item) {
List<T> list = new ArrayList<T>(Arrays.asList(arr));
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == item) {
list.remove(i);
}
}
return list.toArray(arr);
}
EDIT:
After reading through some of the answer I've changed the removeArrayElement to this:
public static <T> T[] removeArrayElement(T[] arr, T item) {
for (Iterator<T> iterator = list.iterator(); iterator.hasNext();) {
T t = iterator.next();
if (t == item) {
iterator.remove();
}
}
return list.toArray(arr);
}
but it still for some reason sends this: java.lang.ArrayIndexOutOfBoundsException
EDIT2: Full executable
bankContents[bankSlots[0]] = Utils.removeArrayElement(bankContents[bankSlots[0]], newbankVarient);
When newBankVarient is = bankContents[bankSlots[0]][1] and removing it, System out of array AFTER is:
"[var, var, var, null]