
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Delete Elements from an Array
To delete an element at a particular position from an array. Starting from the required position, replace the element in the current position with the element in the next position.
Example
public class DeletingElementsBySwapping { public static void main(String args[]) { int [] myArray = {23, 93, 56, 92, 39}; System.out.println("hello"); int size = myArray.length; int pos = 2; for (int i = pos; i<size-1; i++) { myArray[i] = myArray[i+1]; } for (int i=0; i<size-1; i++) { System.out.println(myArray[i]); } } }
Output
hello 23 93 92 39
Alternate solution
Apache Commons provides a library named org.apache.commons.lang3 and, following is the maven dependency to add the library to your project.
<dependencies> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.0</version> </dependency> </dependencies>
This package provides a class known as ArrayUtils. Using the remove()method of this class instead of swapping elements, you can delete them.
Example
import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; public class DeletingElements { public static void main(String args[]) { int [] myArray = {23, 93, 56, 92, 39}; int [] result = ArrayUtils.remove(myArray, 2); System.out.println(Arrays.toString(result)); } }
Output
[23, 93, 92, 39]
Advertisements