Shorten array length once element is remove in Java

前端 未结 5 1729
庸人自扰
庸人自扰 2021-01-13 10:00

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

5条回答
  •  醉梦人生
    2021-01-13 10:57

    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,

    1. Create new array with a length of setElements.length - 1.

    2. 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.

    3. Set setElements to the new array if you want to keep using the same variable for your array.

提交回复
热议问题