Как удалить элемент из массива java
Перейти к содержимому

Как удалить элемент из массива java

  • автор:

How do I remove objects from an array in Java?

Given an array of n Objects, let’s say it is an array of strings, and it has the following values:

What do I have to do to delete/remove all the strings/objects equal to «a» in the array?

Peter Mortensen's user avatar

ramayac's user avatar

20 Answers 20

[If you want some ready-to-use code, please scroll to my «Edit3» (after the cut). The rest is here for posterity.]

Edit: I’m now using Arrays.asList instead of Collections.singleton : singleton is limited to one entry, whereas the asList approach allows you to add other strings to filter out later: Arrays.asList(«a», «b», «c») .

Edit2: The above approach retains the same array (so the array is still the same length); the element after the last is set to null. If you want a new array sized exactly as required, use this instead:

Edit3: If you use this code on a frequent basis in the same class, you may wish to consider adding this to your class:

Then the function becomes:

This will then stop littering your heap with useless empty string arrays that would otherwise be new ed each time your function is called.

cynicalman’s suggestion (see comments) will also help with the heap littering, and for fairness I should mention it:

I prefer my approach, because it may be easier to get the explicit size wrong (e.g., calling size() on the wrong list).

C. K. Young's user avatar

An alternative in Java 8:

Make a List out of the array with Arrays.asList() , and call remove() on all the appropriate elements. Then call toArray() on the ‘List’ to make back into an array again.

Not terribly performant, but if you encapsulate it properly, you can always do something quicker later on.

You can always do:

You can use external library:

It is in project Apache Commons Lang http://commons.apache.org/lang/

Pritam Banerjee's user avatar

bugs_'s user avatar

Ali's user avatar

If you need to remove multiple elements from array without converting it to List nor creating additional array, you may do it in O(n) not dependent on count of items to remove.

Here, a is initial array, int. r are distinct ordered indices (positions) of elements to remove:

In your task, you can first scan array to collect positions of «a», then call removeItems() .

There are a lot of answers here—the problem as I see it is that you didn’t say WHY you are using an array instead of a collection, so let me suggest a couple reasons and which solutions would apply (Most of the solutions have already been answered in other questions here, so I won’t go into too much detail):

reason: You didn’t know the collection package existed or didn’t trust it

solution: Use a collection.

If you plan on adding/deleting from the middle, use a LinkedList. If you are really worried about size or often index right into the middle of the collection use an ArrayList. Both of these should have delete operations.

reason: You are concerned about size or want control over memory allocation

solution: Use an ArrayList with a specific initial size.

An ArrayList is simply an array that can expand itself, but it doesn’t always need to do so. It will be very smart about adding/removing items, but again if you are inserting/removing a LOT from the middle, use a LinkedList.

reason: You have an array coming in and an array going out—so you want to operate on an array

solution: Convert it to an ArrayList, delete the item and convert it back

reason: You think you can write better code if you do it yourself

solution: you can’t, use an Array or Linked list.

reason: this is a class assignment and you are not allowed or you do not have access to the collection apis for some reason

assumption: You need the new array to be the correct «size»

solution: Scan the array for matching items and count them. Create a new array of the correct size (original size — number of matches). use System.arraycopy repeatedly to copy each group of items you wish to retain into your new Array. If this is a class assignment and you can’t use System.arraycopy, just copy them one at a time by hand in a loop but don’t ever do this in production code because it’s much slower. (These solutions are both detailed in other answers)

reason: you need to run bare metal

assumption: you MUST not allocate space unnecessarily or take too long

assumption: You are tracking the size used in the array (length) separately because otherwise you’d have to reallocate your array for deletes/inserts.

An example of why you might want to do this: a single array of primitives (Let’s say int values) is taking a significant chunk of your ram—like 50%! An ArrayList would force these into a list of pointers to Integer objects which would use a few times that amount of memory.

solution: Iterate over your array and whenever you find an element to remove (let’s call it element n), use System.arraycopy to copy the tail of the array over the «deleted» element (Source and Destination are same array)—it is smart enough to do the copy in the correct direction so the memory doesn’t overwrite itself:

You’ll probably want to be smarter than this if you are deleting more than one element at a time. You would only move the area between one «match» and the next rather than the entire tail and as always, avoid moving any chunk twice.

Как удалить элемент массива в Java?

В некоторых случаях возникает необходимость в удалении элементов из Java-массива. Однако язык программирования Java не предоставляет для выполнения этой операции прямого метода. Тем не менее ряд способов всё же имеется. О них и поговорим.

Начнём с того, что в обычном массиве удаление осуществляется не очень удобно. То есть мы не можем просто взять и удалить ячейку из Java-массива. Зато можем обнулить значение этой ячейки.

Итак, мы видим, что кот Вася благополучно обнулился. Однако при выполнении такой операции в Java-массиве остаётся «дыра», поскольку мы удаляем лишь содержимое ячейки, но не саму ячейку. То есть мы получаем пустую ячейку в середине массива, что не есть хорошо.

Что тут можно сделать? Например, переместить эту ячейку в самый конец массива, сдвинув другие элементы к началу:

Всё стало лучше, но, согласитесь, такое решение сложно назвать стабильным. Хотя бы потому, что каждый раз, когда нам надо будет удалить элемент из массива, нам придётся повторять вышеописанную операцию.

Использование ArrayList

Если гора не идёт к Магомету, Магомет идёт к горе. Если мы не можем удалить элемент в обычном массиве, мы можем преобразовать массив в структуру, позволяющую удалять элементы. А потом преобразовать эту структуру обратно в массив.

Выполнить вышеописанную схему нам поможет java.util.List или ArrayList. Дело в том, что в ArrayList реализован специальный метод, позволяющий удалять элементы — remove. В общем виде всё выглядит так:

Давайте теперь рассмотрим работу метода remove на наших котах:

Итак, мы передали в метод индекс нашего объекта, в результате чего он был удален.

Тут следует отметить следующие особенности метода remove() : — он не оставляет так называемых «дыр» — в нём реализована логика сдвига элементов, если мы удаляем элемент из середины. Вот вывод предыдущего кода:

То есть после удаления одного кота, остальные были передвинуты, и пробелов не осталось.

Кроме того, remove способен удалять объект не только по индексу, но и по ссылке:

Однако на просторах сети можно найти и другие способы удаления нужных элементов из массива.

Используем System.arraycopy

Мы можем просто создать копию исходного массива с помощью System.arraycopy(), удалив таким нехитрым способом соответствующий элемент:

Используем Apache Commons Lang

Последний способ, о котором стоит упомянуть, — применение библиотеки Apache Commons Lang и статического метода removeElement() класса ArrayUtils:

Apache Commons предоставляет нам библиотеку с именем org.apache.commons.lang3. Добавить библиотеку в ваш проект можно с помощью следующей maven-зависимости:

Данный пакет предоставляет класс ArrayUtils. Используя метод remove() этого класса, можно удалять элементы. Рассмотрим это на примере удаления повторяющихся элементов в массиве Java. Для обнаружения дублей надо сравнить каждый элемент Java-массива с оставшимися, для чего можно использовать 2 вложенных цикла.

Удалить определенный элемент из массива в Java

В этом посте будет обсуждаться, как удалить определенный элемент из массива в Java.

Массивы в Java имеют фиксированную длину. Это означает, что они содержат фиксированное количество значений одного типа. Длина массива определяется при его создании. После создания его длина фиксируется.

Поскольку длина массива фиксирована, нет стандартного способа удалить из него элементы. Однако вы можете создать новый массив, содержащий все элементы исходного массива, кроме того, который вы хотите удалить. Есть несколько способов добиться этого в Java:

1. Использование библиотеки Apache Commons Lang

Apache Commons Lang's ArrayUtils класс предлагает removeElement() метод для удаления первого вхождения указанного элемента из указанного массива. Он перегружен, чтобы принимать все примитивные типы и массивы объектов. Ниже приведен простой пример, демонстрирующий его использование.

How to Remove Array Elements in Java

How to Remove Array Elements in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

When we create an array in Java, we specify its data type and size. This is used by JVM to allocates the necessary memory for array elements. There are no specific methods to remove elements from the array.

1. Removing an element from Array using for loop

This method requires the creation of a new array. We can use for loop to populate the new array without the element we want to remove.

Arr Delete

The code removes the element at index 3. This method simply copies all the elements except the one at index 3 to a new array.

2. Deleting an array element by its value

Unlike the previous case, this code will delete the element based on its value. This will not work with duplicates since the size of the array after deletion has to be known.

Arr Delete based on value

The only difference between this and the previous case is arr[i]!=j in the if condition in place of i!=j .

3. Deleting element by its value when the array contains duplicates

Performing deletion based on the value in case of duplicates requires using ArrayList. Since ArrayList doesn’t require the size to be now in advance, it allows us to expand dynamically.

array-deletion-duplicates

4. Shifting elements in the same array

This method involves shifting the elements in the same array. Shifting of elements replaces the element to be deleted by the element at the next index.

Count variable indicates the number of elements deleted. This variable is essential to keep a track of index till which the array should be printed. This method takes care of duplicates as well.

Shifting Elements In Array

5. Deleting elements from ArrayList

ArrayList is backed by arrays. The deletion of an element in the ArrayList is straight forward. It requires one simple call to an inbuilt function.

A call to the remove(i) function removes the element at index i. Deletion in ArrayLists is relatively easier as compared to Arrays.

ArrayList Deletion

Conclusion

We saw some examples of deleting elements in an array using different methods. The difference between the deletion of an element in an Array and an ArrayList is clearly evident. If deletion is to be performed again and again then ArrayList should be used to benefit from its inbuilt functions. Same is the case with the addition of elements to an array. ArrayList due to its dynamic nature provides easier and less cumbersome ways to alter an array.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *