How do i remove an element from an Array in java without getting: java.lang.ArrayIndexOutOfBoundsException?

I want to remove an index from and array and have tried to do so by copying over all the elements except the one that I want to remove in to a new array, however my solution gets ArrayIndexOutOfBoundsException, what should I do to solve this?

public void removeItem(Item item) {

 
        Item[] ownedItemCopy  = new Item [ownedItem.length - 1 ];
            
            for (int i = 0; i < ownedItem.length; i++) { 
                
                if(!ownedItem[i].equals(item)) {
                int j=i;    
                    
                
                    
                    ownedItemCopy[j-1]=ownedItem[i];
                    
                }
                
                
            }
            ownedItem=ownedItemCopy;
        }


Read more here: https://stackoverflow.com/questions/66336006/how-do-i-remove-an-element-from-an-array-in-java-without-getting-java-lang-arra

Content Attribution

This content was originally published by tewi at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: