java 删除数组中某一个元素的方法
时间: 2023-04-07 09:02:53 浏览: 118
可以使用 System.arraycopy() 方法将要删除元素后面的元素向前移动,然后将最后一个元素设为 null。具体代码如下:
int[] arr = {1, 2, 3, 4, 5};
int index = 2; // 要删除的元素下标
int len = arr.length;
if (index >= 0 && index < len) {
System.arraycopy(arr, index + 1, arr, index, len - index - 1);
arr[len - 1] = 0; // 将最后一个元素设为 null 或 0
}
System.out.println(Arrays.toString(arr)); // [1, 2, 4, 5, 0]
相关问题
java实现删除数组中某一个元素的方法
可以使用 System.arraycopy() 方法将要删除元素之前和之后的元素复制到一个新的数组中,从而实现删除元素的效果。具体实现方法可以参考以下代码:
public static int[] removeElement(int[] arr, int index) {
if (arr == null || index < 0 || index >= arr.length) {
return arr;
}
int[] newArr = new int[arr.length - 1];
System.arraycopy(arr, 0, newArr, 0, index);
System.arraycopy(arr, index + 1, newArr, index, arr.length - index - 1);
return newArr;
}
Java从数组中删除一个元素并输出
可以使用Java中的ArrayList类来删除数组中的元素,具体代码如下:
```
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> arrList = new ArrayList<Integer>();
arrList.add(1);
arrList.add(2);
arrList.add(3);
arrList.add(4);
arrList.add(5);
// 删除第三个元素
arrList.remove(2);
// 输出剩余元素
for (int i = 0; i < arrList.size(); i++) {
System.out.println(arrList.get(i));
}
}
}
```
输出结果为:
```
1
2
4
5
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)