package test2; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * 迭代器 * * @author Administrator */ public class Test4 { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("qqqq"); list.add("wwww"); list.add("eeee"); Iterator<String> iter = list.iterator(); while(iter.hasNext()) { String s = iter.next(); System.out.println(s); if (s.equals("wwww")) { // iter.remove(); list.remove(iter.next()); //尽量不要调用两次iter.next } } System.out.println(list); ListIterator<String> ls = list.listIterator(); while(ls.hasPrevious()) { System.out.println(ls.previous()); } /* * 需要注意的问题: * 迭代器中的remove方法, 绝对不可以与list中的remove(Object)方法混用 * 会抛出ConcurrentModificationException这个异常 * next方法的调用 */ } }
package test2; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class Test3 { public static void main(String[] args) { String[] arrs = {"aa","bb","cc","dd","aa","cc","ee","ee","cc","aa"}; // 查询数组内字母出现了几次 List<String> list = new ArrayList<>(); list.add("qqqq");list.add("wwww");list.add("eeee"); Set<String> set = new HashSet<>(); set.add("1111");set.add("22222222222");set.add("3333333"); for(String s1 : arrs) { System.out.println(s1); } for (String s2 : list) { System.out.println(s2); } for (String s3 : set) { System.out.println(s3); } /* Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < arrs.length; i++) { // map.put(arrs[i], map.get(arrs[i]) == null ? 1 : map.get(arrs[i]) + 1); Integer count = map.get(arrs[i]); if (count == null) { map.put(arrs[i], 1); } else { map.put(arrs[i], count + 1); } } System.out.println(map);*/ } }