静网PWA视频评论

java如何删除集合中的元素

2024年01月04日

- txt下载

java如何删除集合中的元素
如何使用java删除集合中的元素呢?下面是小编给大家提供的.删除集合中元素的常见方法,欢迎阅读,更多详情请关注应届毕业生考试网。
  Java代码如下:
package com.jerval.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* <b>Description</b>:
* <p>
* <b>Features or change log:</b>
* <ol>
* <li>2014年1月21日 上午10:58:21, jervalj, C001:</li>
* <li></li>
* </ol>
*/
public class TestMain {
public static void main(String[] args) {
removeItem1();
removeItem2();
removeItem3();
}
private static void removeItem1() {
List<Integer> list = getList();
// 使用迭代器
Iterator<Integer> iter = list.iterator();
Integer item = null;
while (iter.hasNext()) {
item = iter.next();
if (null != item && 5 == item.intValue()) {
iter.remove();
}
}
System.out.println(list);
}
private static void removeItem2() {
List<Integer> list = getList();
// 手动索引操作
int len = list.size();
Integer item = null;
for (int i = 0;i < len;i++) {
item = list.get(i);
if (null != item && 5 == item.intValue()) {
list.remove(item);
i--;
len--;
}
}
System.out.println(list);
}
private static void removeItem3() {
List<Integer> list = getList();
// 使用引用克隆
List<Integer> listCopy = new ArrayList<Integer>();
listCopy.addAll(list);
for (Integer item:list) {
if (null != item && 5 == item.intValue()) {
listCopy.remove(item);
}
}
System.out.println(listCopy);
}
private static List<Integer> getList() {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0;i < 10;i++) {
list.add(i);
}
return list;
}
}
  Java代码运行结果:
[0, 1, 2, 3, 4, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 6, 7, 8, 9]

收藏

相关推荐

清纯唯美图片大全

字典网 - 试题库 - 元问答 - 繁體 - 顶部

Copyright © cnj8 All Rights Reserved.