package com.heima.gaoshuai;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
/**
* 一个ArrayList中存有若干个字符串元素,现欲遍历该ArrayList对象,删除其中所有值为"abc"的字符串元素,
* 请用代码实现。(两种方式)
* @author Administrator
*
*/
public class Test3 {
public static ArrayList getSingle1(ArrayList<String> list){
ArrayList list1 = new ArrayList();
ListIterator<String> it = list.listIterator();
while(it.hasNext()){
String str = it.next();
if(list1.contains(str)){
it.remove();
}
list1.add(str);
}
return list;
}
public static ArrayList getSingle2(ArrayList list){
ArrayList list1 = new ArrayList();
list1 = list;
for(int i=0;i<list1.size();i++){
for(int j=i+1;j<list1.size();j++){
if(list.get(i).equals(list1.get(j))){
list.remove(j);
}
}
}
return list1;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("abc");
list.add("abc");
list.add("abc");
list.add("ghi");
list.add("def");
list.add("ghi");
list = getSingle2(list);
System.out.println(list);
}
}
|
|