10

重複の可能性:
配列からの要素の削除 (Java)

たとえば、特定の文字列配列値を削除する方法

String[] str_array = {"item1","item2","item3"};

str_array から「item2」を削除したい 助けてください 次のような出力が必要です

String[] str_array = {"item1","item3"};

4

4 に答える 4

37

私は次のようにします:

String[] str_array = {"item1","item2","item3"};
List<String> list = new ArrayList<String>(Arrays.asList(str_array));
list.remove("item2");
str_array = list.toArray(new String[0]);
于 2012-10-10T05:13:44.657 に答える
11

ArrayUtils API を使用して削除できます。

array = ArrayUtils.removeElement(array, element);
于 2012-10-10T05:27:07.563 に答える
7

アレイを使用する必要がある場合System.arraycopyは、が最も効率的でスケーラブルなソリューションです。ただし、配列から1つの要素を数回削除する必要がある場合は、配列ではなくListの実装を使用する必要があります。

以下はSystem.arraycopy、望ましい効果を達成するために利用します。

public static Object[] remove(Object[] array, Object element) {
    if (array.length > 0) {
        int index = -1;
        for (int i = 0; i < array.length; i++) {
            if (array[i].equals(element)) {
                index = i;
                break;
            }
        }
        if (index >= 0) {
            Object[] copy = (Object[]) Array.newInstance(array.getClass()
                    .getComponentType(), array.length - 1);
            if (copy.length > 0) {
                System.arraycopy(array, 0, copy, 0, index);
                System.arraycopy(array, index + 1, copy, index, copy.length - index);
            }
            return copy;
        }
    }
    return array;
}

また、配列がオブジェクトのみで構成されていることがわかっている場合は、メソッドの効率を上げることができComparableます。Arrays.sortメソッドを通過する前にそれらをソートするために使用でき、forループではなくインデックスを見つけるためremoveに使用するように変更され、メソッドの効率のその部分をO(n)からO(nlogn)に上げます。Arrays.binarySearch

于 2012-10-10T05:41:24.350 に答える
4

その他のオプションは、アイテムを削除するよりも、配列を他の配列にコピーすることです。

 public static String[] removeItemFromArray(String[] input, String item) {
    if (input == null) {
        return null;
    } else if (input.length <= 0) {
        return input;
    } else {
        String[] output = new String[input.length - 1];
        int count = 0;
        for (String i : input) {
            if (!i.equals(item)) {
                output[count++] = i;
            }
        }
        return output;
    }
}
于 2012-10-10T05:28:20.687 に答える