Java如何删除数组中的元素?


Java中,如何删除数组元素?

示例

以下示例显示如何从数组中删除元素。

package com.yiibai; import java.util.ArrayList; public class RemoveArrayElement { public static void main(String[] args) { ArrayList objArray = new ArrayList(); objArray.clear(); objArray.add(0, "0th element"); objArray.add(1, "1st element"); objArray.add(2, "2nd element"); System.out.println("Array before removing an element" + objArray); objArray.remove(1); objArray.remove("0th element"); System.out.println("Array after removing an element" + objArray); } } 
Java

执行上面示例代码,得到以下结果 -

Array before removing an element[0th element, 1st element, 2nd element]
Array after removing an element[2nd element]
Shell

示例2

数组删除的另一个示例示例

package com.yiibai; import java.util.*; public class RemoveArrayElement2 { public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>(5); arr.add(220); arr.add(115); arr.add(320); arr.add(145); System.out.println("Size of list: " + arr.size()); for (Integer number : arr) { System.out.println("Number = " + number); } arr.remove(2); System.out.println("After remove, Size of list: " + arr.size()); for (Integer number : arr) { System.out.println("Number = " + number); } } } 
Java

执行上面示例代码,得到以下结果 -

Size of list: 4
Number = 220
Number = 115
Number = 320
Number = 145
After remove, Size of list: 3
Number = 220
Number = 115
Number = 145


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM