Note: Following is my homework/assignment, feel free not to answer if you will.
I want to delete/remove an element from an String array(Set) basic, I\'m not allowe
All that setElements[i] = "";
does is change the value of an element in the array. It does not actually remove anything from the array. If you were using a collection class and called remove(i)
on it, then you would actually be removing that element from the collection. But here, you're just changing its value. However, arrays in Java have a fixed size and cannot be resized, so there is no way to remove elements from them. The solution, therefore, is to create a new array with a length one shorter than the old one, and then copy all of the values that you want to keep into the new one. So,
Create new array with a length of setElements.length - 1
.
Copy all of the elements in setElements
into the new array, except for the one which you're looking to remove. Be careful of the fact that the indices into the two arrays will be off by one rather than equal once you've reached the index for the element that you wish to remove.
Set setElements
to the new array if you want to keep using the same variable for your array.