一、集合中的迭代器

1.创建迭代器遍历有2步

  1. 创建迭代对象
  2. 开始迭代

    1. //创建集合对象
    2. Collection c = new ArrayList();
    3. c.add("add");
    4. c.add("wqe");
    5. //创建迭代器对象
    6. Iterator it = c.iterator();
    7. //开始迭代
    8. while (it.hasNext()){
    9. Object obj = it.next();
    10. System.out.println(obj);
    11. }
    12. /*
    13. if(it.hasNext()){
    14. Object obj = it.next();
    15. System.out.println();
    16. }
    17. */

    2.HashSet集合

  • 无序
  • 不重复

    1. //HashSet 集合:无序不可重复
    2. Collection c2 = new HashSet();
    3. c2.add(100);
    4. c2.add(200);
    5. c2.add(50);
    6. c2.add(60);
    7. c2.add(900);
    8. Iterator it2 = c2.iterator();
    9. while (it2.hasNext()){
    10. System.out.println(it2.next());
    11. }

二、Collection方法

1.深入Collection集合的contains方法

contains底层调用了equals方法,String中重写了equals方法,比较的是内容
image.png

  1. package collection;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. public class Test02 {
  5. public static void main(String[] args) {
  6. Collection c = new ArrayList();
  7. String s1 = new String("abc");
  8. c.add(s1);
  9. System.out.println("元素的个数是:"+c.size());
  10. String x = new String("abc");
  11. System.out.println(c.contains(x));//true
  12. }
  13. }