如何从String数组中删除元素?重要提示:我不想将我的数组转换为List

Ned*_*nic -1 java

我有一个Generic方法smallestValueInArray(T[] array),这个方法得到一个任何类型的数组.此方法如下所示:

public class Helper {

    public static <T extends Comparable<T>> T smallestValueInArray(T[] array) {
        T smallestValue = array[0];
        T smallerTempValue = array[0];

        for (int i = 0; i < array.length - 2; i+=2) {

            if (array[i].compareTo(array[i+1]) < 0) {
                smallerTempValue = array[i];
            } else {
                smallerTempValue = array[i+1];
            }

            if (smallestValue.compareTo(smallerTempValue) > 0) {
                smallestValue = smallerTempValue;
            }
        }
        return smallestValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

在Main方法中我想做这样的事情:

for (int i = 0; i < stringArray.length; i++) {
        someOtherArray[i] = Helper.smallestValueInArray(stringArray);
        Helper.deleteElement(stringArray, stringArray[i]);
    }
Run Code Online (Sandbox Code Playgroud)

所以我想循环stringArray,找到该数组中的最小元素,并将该元素添加到新数组someOtherArray.之后我想使用一个方法deleteElement(),这个方法得到两个参数,第一个是一个数组,第二个是该数组中应删除的元素位置.

我的deleteElement()方法应该怎么样?

重要提示:我不想在List中转换我的数组,而是使用list.remove()!

Era*_*ran 5

如果您不想将数组转换为a List,我看到的唯一选项是创建一个不包含已删除元素的新数组.您的deleteElement方法必须返回该数组.

public static <T> T[] deleteElement(T[] array, int i)
{
    // create new array of length array.length - 1
    // copy all the elements from the source array except of the i'th element
    // return the new array
}
Run Code Online (Sandbox Code Playgroud)

你会用它来称呼它:

stringArray = Helper.deleteElement (stringArray, i);
Run Code Online (Sandbox Code Playgroud)

当然,将数组转换为ArrayList,删除i第th个元素并转换回数组会更简单.