package cn.sdut.chapter5;
import java.util.*;
/*
* ArrayList去除集合中字符串的重复值(字符串的内容相同)
*/
public class List04 {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("java");
list.add("web");
list.add("ssss");
list.add("java");
list.add("java");
list.add("ssss");
// 边迭代边删除
// method1(list);
method2(list);
print(list);
}
private static void method2(List<String> list) {
for (int i = 0; i < list.size() - 1; i++) {
for (int j = list.size() - 1; j > i; j--) {
if (list.get(i).equals(list.get(j))) {
list.remove(j);
}
}
}
}
private static void method1(List<String> list) {
List<String> list1 = new ArrayList<>();
for (Iterator<String> it = list.iterator(); it.hasNext();) {
String str = it.next();
if (list1.contains(str)) {
it.remove();// 边迭代边删除
} else {
list1.add(str);
}
}
}
private static void print(Collection<String> list) {
for (String str : list) {
System.out.println(str);
}
}
}
ArrayList去除集合中字符串的重复值(字符串的内容相同)
最新推荐文章于 2023-08-20 19:02:43 发布